First of all there is a question with the same title here on SO but its not what I'm looking for and it doesn't have a complete answer either.
So here's my question. Say I have this URL which directs to an image.
https://fbcdn-photos-a.akamaihd.net/hphotos-ak-ash4/299595_10150290138650735_543370734_8021370_355110168_n.jpg
Once I put this parameter ?dl=1
to the end of the URL, it becomes downloadable.
https://fbcdn-photos-a.akamaihd.net/hphotos-ak-ash4/299595_10150290138650735_543370734_8021370_355110168_n.jpg?dl=1
I'm trying to do this task through a userscript. So I used XMLHttpRequest for that.
var url = "https://fbcdn-photos-a.akamaihd.net/hphotos-ak-ash4/299595_10150290138650735_543370734_8021370_355110168_n.jpg?dl=1";
var request = new XMLHttpRequest();
request.open("GET", url, false);
request.send(null);
if (request.status === 200)
{
alert(request.statusText);
}
Here is a fiddle.
But it does not work.
You are trying to request a resource using XHR that is on a different domain and is thus blocked. Use CORS for cross-domain messaging using XHR.
Modern browsers have the Blob object:
The
headers
param will set the referrer so you can load referrer locked images.XMLHttpRequest
will not work cross-domain, but since this is a userscript Chrome now supportsGM_xmlhttpRequest()
in userscripts only.Something like this should work, note that it is asynchronous:
As for getting and using the actual image data, that is a major pain to work out.
You can use the new
.responseType = "blob";
functionality in Firefox but Chrome does not yet support it.In Chrome or Firefox, for the same domain only, you can use the new XHR2 like so:
See it in action at jsBin.
GM_xmlhttpRequest()
does not (yet) support settingresponseType
.So, for GM script or userscript applications, we have to use a custom base64 encoding scheme like in "Javascript Hacks: Using XHR to load binary data".
The script code becomes something like:
Krof Drakula is right, you cannot load an image from a different domain, but do you really need to do this? You can create and append an
img
tag and wait for it to load (with something like jQueryload()
).