未处理的拒绝在Chrome中无效

Jos*_*ley 6 javascript google-chrome promise

我正在尝试在Google Chrome中使用一个简单的未处理注释处理程序.

如果我将以下代码粘贴到JSFiddle并在Chrome中运行它,我会得到一个错误框,如预期的那样:

window.addEventListener('unhandledrejection', function(e) {
    console.log(e);
    alert(e.reason);
});
new Promise(function(resolve, reject) {
    setTimeout(function() {
        return reject('oh noes');
    }, 2000);
});
Run Code Online (Sandbox Code Playgroud)

如果我创建一个包含嵌入式脚本的HTML文件并将其作为file:///URL 加载到Chrome中,我会按预期收到一个消息框.

<!doctype html>
<html>
<body>
  <script type="text/javascript">
    window.addEventListener('unhandledrejection', function(e) {
        console.log(e);
        alert(e.reason);
    });
    new Promise(function(resolve, reject) {
        setTimeout(function() {
            return reject('oh noes');
        }, 2000);
    });
  </script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

如果我创建单独的HTML和JS文件并将其作为file:///URL 加载到Chrome中,我会获得Chrome标准的"未捕获(承诺)"控制台错误,但没有消息框.

index.html的:

<!doctype html>
<html>
<body>
  <script type="text/javascript" src="app.js"></script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

app.js:

window.addEventListener('unhandledrejection', function(e) {
    console.log(e);
    alert(e.reason);
});
new Promise(function(resolve, reject) {
    setTimeout(function() {
        return reject('oh noes');
    }, 2000);
});
Run Code Online (Sandbox Code Playgroud)

这是怎么回事?

Jos*_*ley 10

据我所知,原因是如果"unhandledrejection"事件处理程序源自不同的脚本原点,则会被忽略.(有关详细信息,请参阅同源策略的 MDN .)Chrome 对文件URL的安全起源非常严格,但我发现在不知情的情况下打破相同的原始策略也可能由于其他原因(例如开发中)打开Chrome开发工具的webpack-dev-server).请参阅此Chrome问题以供讨论.

解决方法是在更简单,更接近生产的环境中进行测试:在纯HTTP服务器上运行(SimpleHTTPServer运行良好),必要时关闭Dev Tools.