在Chrome中的onbeforeunload期间,GM_xmlhttpRequest不起作用

时间:2014-05-10 14:50:40

标签: javascript ajax google-chrome userscripts onbeforeunload

在我的脚本中,GM_xmlhttpRequest不起作用,但定期xmlhttpRequest会这样做。 (但我需要GM_xmlhttpRequest因为调用是跨域的。)

window.onbeforeunload = function (){
    try{
        details = GM_xmlhttpRequest({
           method: "GET",
           url: "http://www.example.com",
           synchronous: true // this been tried with both possible values
        });
        console.log(details); // Object {abort: function}
    }
    catch(e){ // catch is not being triggered
        console.log(e);   
    }
    return "dontleave";
}

相同的代码完全符合Firefox的预期(首先是AJAX,然后是继续)。

常规xmlhttpRequest也会在该位置执行应有的操作(但它不允许跨域调用)。

有什么问题?

1 个答案:

答案 0 :(得分:2)

简而言之,问题的产生是因为Tampermonkey(处理Chrome中用户脚本的插件)不完全支持GM_xmlhttpRequest - 它不允许同步调用。更糟糕的是,Chrome本身会在unbeforeunload期间阻止执行任何异步回调(将它们延迟到ununload)。

我们发现绝对没有可接受的方法,不得不放弃脚本并让用户使用功能有限的Chrome替代品。