I was working on a userscript last week to facilitate downloading and saving images from a facebook album. I wanted to automate this, rather than have to manually open and save each picture. The Greasemonkey add-on to Firefox seemed like the best way to get this done, and before long I had a bit of JavaScript that could fetch and save a file to my local disk with no user interaction. In the spirit of logging things I might want to come back to later, join saving other people the frustration I experienced with all my searches finding metablogs referring to the same ghostblog, I briefly document what I needed.
First, it seems sensible to cover downloading binary data via Javascript. I used the XMLHttpRequest object for this, which I created in this cross-browser way:
var oXML=window.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest();
My first attempts at downloading images would produce data, but not a viable image. It turned out to be affected by the way XMLHttpRequest process the HTTP response, which seemed hopeless at first, but proved to be easy to resolve, given the right information. Fetching binary data is a two-step process. The request needs to be configured properly, and the response requires some processing to restore the data to it's original form. The configuration of the request is simple, one additional line of code:
more...