Saturday, November 14, 2009

Inline Downloads with Data URLs

A quick post about another silly idea ...
With Data URLs we can incorporate images in layout or CSS.
The schema is really simple:

data:[<mediatype>][;base64],<data>

Since we need to specify a mediatype we could play around creating something unexpected ;-)

My Silly Idea

If we select something in a web page we can perform different actions via right click. So far so good ... but one thing we are missing, at least in Firefox, is a "Save As" option. If we want bring a piece of code, text, something else, into another software or editor we need to select, right click, copy, open or find the editor, right click, paste.
The ultra skilled developers goes well with ctrl+c and ctrl+v but there are still 3 operations to do: copy, find the destination, paste
What about making possible to simply save that part and go on reading or surfing in order to do not distract too much our lecture and review eventually later that piece of text or code?

Firefox Inline Download


function download(text){
// Yet Another Silly WebReflection Experiment
var iframe = document.createElement("iframe");
iframe.src = "data:application/octet-stream;base64," + btoa(text);
iframe.style.position = "absolute";
iframe.style.top = "-10000px";
document.documentElement.insertBefore(
iframe,
document.documentElement.firstChild
);
};

download("Hello World :-)");

If we have configured Firefox to ask us where to save files, we can even choose the name. Being the inline data protocol that simple, unfortunately I could not find a way to name the file. The concept in any case is simple, we could create a bookmark or a link able to save the selected text, if any.
In this case we select, and with a click we can directly organize the content in a named file or we can open it with the editor that will be probably the first option in the Open With question.

Side Effects

Well, the first one is that I am not even sure if this could be considered a security problem, and I am testing in Firefox 3.6 beta 2 (so I am not even sure this is possible with other versions).
We cannot remove the iframe until the user has saved the content and never before the save dialog will be showed, otherwise a generic onload will remove the content before Firefox can understand what to do.
On the other hand, since the content will be inline, the "Open With" should always work 'cause Firefox, which is a clever browser, saves and eventually remove, even if we cancel the operation.

Conclusion

Nobody will probably ever use above snippet, but I thought it was an interesting and new way to manipulate a technique used for totally different purposes (OK, I have to admit the only excuse I have is my new netbook and I had to test some code after Notepad++ installation :D)

No comments:

Post a Comment