Ajax: How to know if a user script implementation doesn't set the Origin header?

冷暖自知 提交于 2020-01-30 12:08:44

问题


Some user script implementations (like Google Chrome) allow direct cross AJAX requests, but some others don't, and use Same Origin Policy restrictions. Here's a part of code:

/*
 * 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);
}

The result is the server (https://cors-anywhere.herokuapp.com/) sends a 400 error telling theOriginheader is missing. Browsers doesn't allows to set theOriginheader so a quick and dirty hack would be to set the customx-requested-with. If an old browser set theOriginheader correctly, this make a duplicate ofx-requested-with. Here's would be code :

ajax.setRequestHeader('x-requested-with', document.domain); // chrome doesn't support setting the 'Origin' header automatically.

I can't use try statements since synchronous AJAX requests got deprecated nor I can set the Origin header. So, How I can know if the browser doesn't set a particular header?

来源:https://stackoverflow.com/questions/26247041/ajax-how-to-know-if-a-user-script-implementation-doesnt-set-the-origin-header

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!