不推荐使用同步 XMLHttpRequest

Joh*_*ith 5 ajax xmlhttprequest synchronous deprecated chromium

今天,由于扩展程序的一些问题,我不得不重新启动浏览器。当我重新启动它时,我发现我的浏览器 (Chromium) 自动更新到一个不再允许同步 AJAX 请求的新版本。引用:

主线程上的同步 XMLHttpRequest 已被弃用,因为它会对最终用户的体验产生不利影响。如需更多帮助,请查看http://xhr.spec.whatwg.org/

我的 node.js 应用程序需要同步 AJAX 请求才能工作,因为它们通过使用 fopen 的服务器从磁盘存储和加载数据。我发现这是一种非常简单有效的做事方式,在创建小型爱好项目和编辑器时非常方便......有没有办法在 Chrome/Chromium 中重新启用同步 XMLHttpRequests?

use*_*831 1

该答案已被编辑。

简短的回答: 他们不希望在线程上同步。

对于支持线程/网络工作者的新浏览器来说,解决方案很简单:

var foo = new Worker("scriptWithSyncRequests.js")
Run Code Online (Sandbox Code Playgroud)

DOM 和全局变量在工作线程中都不可见,但封装多个同步请求将非常容易。

替代解决方案是切换到异步,但使用浏览器localStorage和 JSON.stringify 作为媒介。如果您允许执行一些 IO,您也许能够模拟 localStorage。 http://caniuse.com/#search=localstorage

只是为了好玩,如果我们想仅使用同步来限制自己,还有其他替代方法:

使用 setTimeout 很诱人,因为人们可能认为这是将同步请求封装在一起的好方法。不幸的是,有一个陷阱。JavaScript 中的异步并不意味着它可以在自己的线程中运行。异步可能会推迟调用,等待其他人完成。对我们来说幸运的是,隧道尽头有曙光,因为您很可能可以使用 xhttp.timeout 和 xhttp.ontimeout 来恢复。请参阅Timeout XMLHttpRequest 这意味着我们可以实现一个小型版本的调度程序,用于处理失败的请求并分配时间重试或报告错误。

// The basic idea.
function runSchedular(s)
{
    setTimeout(function() {
        if (s.ptr < callQueue.length) {
            // Handles rescheduling if needed by pushing the que.
            // Remember to set time for xhttp.timeout.
            // Use xhttp.ontimeout to set default return value for failure.
            // The pushed function might do something like: (in pesudo)
            // if !d1
            // d1 = get(http...?query);
            // if !d2
            // d2 = get(http...?query);
            // if (!d1) {pushQue tryAgainLater}
            // if (!d2) {pushQue tryAgainLater}
            // if (d1 && d2) {pushQue handleData}
            s = s.callQueue[s.ptr++](s);
        } else {
            // Clear the que when there is nothing more to do.
            s.ptr = 0;
            s.callQueue = [];
            // You could implement an idle counter and increase this value to free
            // CPU time.
            s.t = 200;
        }
        runSchedular(s);
    }, s.t);
}
Run Code Online (Sandbox Code Playgroud)