< p >
XMLHttpRequest
不能跨域工作,但由于这是一个
用户脚本,Chrome现在只支持在用户脚本中使用
GM_xmlhttpRequest()
。
类似下面这样的代码应该可以工作,注意它是异步的:
GM_xmlhttpRequest ( {
method: 'GET',
url: 'https://fbcdn-photos-a.akamaihd.net/hphotos-ak-ash4/299595_10150290138650735_543370734_8021370_355110168_n.jpg?dl=1',
onload: function (responseDetails) {
alert(responseDetails.statusText);
}
} );
获取和使用实际图像数据是一个很大的痛点。
BlobBuilder = window.MozBlobBuilder || window.WebKitBlobBuilder || window.BlobBuilder;
var url = "http://jsbin.com/images/gear.png";
var request = new XMLHttpRequest();
request.open ("GET", url, false);
request.responseType = "arraybuffer";
request.send (null);
if (request.status === 200) {
var bb = new BlobBuilder ();
bb.append (request.response);
var blob = bb.getBlob ('image/png');
var reader = new FileReader ();
reader.onload = function (zFR_Event) {
$("body").prepend ('<p>New image: <img src="' + zFR_Event.target.result + '"></p>')
};
reader.readAsDataURL (blob);
}
很遗憾,GM_xmlhttpRequest()
目前还不支持设置responseType
。
因此,对于GM脚本或用户脚本应用程序,我们必须使用自定义的base64编码方案,就像“Javascript Hacks:Using XHR to load binary data”中所示的那样。
脚本代码变成了这样:
var imgUrl = "http://jsbin.com/images/gear.png";
GM_xmlhttpRequest ( {
method: 'GET',
url: imgUrl,
onload: function (respDetails) {
var binResp = customBase64Encode (respDetails.responseText);
var zImgPara = document.createElement ('p');
var zTargetNode = document.querySelector ("body *");
zImgPara.innerHTML = 'Image: <img src="data:image/png;base64,'
+ binResp + '">';
zTargetNode.parentNode.insertBefore (zImgPara, zTargetNode);
},
overrideMimeType: 'text/plain; charset=x-user-defined'
} );
function customBase64Encode (inputStr) {
var
bbLen = 3,
enCharLen = 4,
inpLen = inputStr.length,
inx = 0,
jnx,
keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
+ "0123456789+/=",
output = "",
paddingBytes = 0;
var
bytebuffer = new Array (bbLen),
encodedCharIndexes = new Array (enCharLen);
while (inx < inpLen) {
for (jnx = 0; jnx < bbLen; ++jnx) {
if (inx < inpLen)
bytebuffer[jnx] = inputStr.charCodeAt (inx++) & 0xff;
else
bytebuffer[jnx] = 0;
}
encodedCharIndexes[0] = bytebuffer[0] >> 2;
encodedCharIndexes[1] = ( (bytebuffer[0] & 0x3) << 4) | (bytebuffer[1] >> 4);
encodedCharIndexes[2] = ( (bytebuffer[1] & 0x0f) << 2) | (bytebuffer[2] >> 6);
encodedCharIndexes[3] = bytebuffer[2] & 0x3f;
paddingBytes = inx - (inpLen - 1);
switch (paddingBytes) {
case 1:
encodedCharIndexes[3] = 64;
break;
case 2:
encodedCharIndexes[3] = 64;
encodedCharIndexes[2] = 64;
break;
default:
break;
}
for (jnx = 0; jnx < enCharLen; ++jnx)
output += keyStr.charAt ( encodedCharIndexes[jnx] );
}
return output;
}