某些用户脚本实现(例如 Google Chrome)允许直接跨 AJAX 请求,但其他一些则不允许,并且使用同源策略限制。这是代码的一部分:
/*
* Get the size of the file.
* @Button the current button for downloading the video.
* @Url the http url of the video.
*/
function SetFileSize(Button, Url) {
var ajax = new XMLHttpRequest();
ajax.onloadend = function () {
GetResolution(Button, Url, ' - ' + (parseInt(this.getResponseHeader("Content-Length")) / 1048576).toFixed(3) + ' Mo')
}
ajax.open('HEAD', Url, true); // <-- HEAD allow to get only the data of the headers.
ajax.send(null);
}
/*
* Retrieve width and height from an MPEG-4 file.
* Width and height are stored as float values, where width come next to height inside binary data.
* There is no fixed place in the file. The method is to get them at 10 bytes before "mdia".
*/
function GetResolution(Button, Url, FileSize) {
var ajax = new XMLHttpRequest();
ajax.onloadend = function () {
var metadata = new DataView(this.response);
for (i = 0;(i < metadata.byteLength) && (metadata.getUint32(i) != 0x6D646961); i += 32) {} // 0x6D646961="mdia"
button.setAttribute('title', metadata.getUint32(i - 14) + 'x' + metadata.getUint32(i - 10) + FileSize);
}
ajax.responseType = 'arraybuffer'; // We want to handle binary data.
ajax.open('GET', Url, true); // <-- the 'false' have been deprecated.
ajax.setRequestHeader('Range', 'bytes=181-300'); // Proceed with a partial download.
ajax.send(null);
}
结果是服务器(https://cors-anywhere.herokuapp.com/
)发送 400 错误告诉Origin
标头丢失。浏览器不允许设置Origin
标头,因此一个快速而肮脏的黑客方法是设置自定义x-requested-with
。如果旧浏览器设置Origin
标题正确,这会复制x-requested-with
。这是代码:
ajax.setRequestHeader('x-requested-with', document.domain); // chrome doesn't support setting the 'Origin' header automatically.
我不能使用尝试语句 http://msdn.microsoft.com/fr-fr/en-uk/library/ie/4yahc5d8(v=vs.94).aspx由于同步 AJAX 请求已被弃用,我也无法设置 Origin 标头。那么,我如何知道浏览器是否未设置特定标头?