javascript - unhandledrejection 在 Chrome 中不起作用

标签 javascript google-chrome promise

我正在尝试获得一个简单的 unhandledrejection在 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);
});

如果我创建一个带有嵌入式脚本的 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>

如果我创建单独的 HTML 和 JS 文件并将其作为 file:/// URL 加载到 Chrome 中,我会收到 Chrome 的标准“Uncaught (in promise)”控制台错误,但没有消息框。

index.html:

<!doctype html>
<html>
<body>
  <script type="text/javascript" src="app.js"></script>
</body>
</html>

应用程序.js:

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

这是怎么回事?

最佳答案

据我所知,原因是如果“unhandledrejection”事件处理程序来自不同的脚本来源,它们将被默默地忽略。 (有关更多信息,请参阅 same-origin policy 上的 MDN。)Chrome 是 very strict特别是文件 URL 的安全来源,但我发现由于其他原因也可能在不知不觉中破坏同源策略(例如在打开 Chrome 开发工具的情况下在 webpack-dev-server 中开发)。参见 this Chrome issue供讨论。

解决方法是在更简单、更接近生产的环境中进行测试:在普通 HTTP 服务器上运行(SimpleHTTPServer 效果很好),必要时关闭开发工具。

关于javascript - unhandledrejection 在 Chrome 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40026381/

相关文章:

javascript - JQuery - 事件绑定(bind)和缓存元素

javascript - 如何在 dropzone.js 中返回每张图片的结果

html - 可以使用 header 为 "Content-Disposition: attachment"的源作为 <img> 的 src 值吗?

css - 即使使用供应商前缀,线性渐变在 Chrome 中也不起作用

javascript - Angular JS : Cannot read property 'then' of undefined

javascript - 加载数据时,Angular 的 Resource Promise 不会重新呈现

javascript - jQuery 多选下拉菜单,带有所选项目的关闭按钮

javascript - Handsontable - 通过 ajax 获取数据并在一列上设置自动完成

Python Selenium : "selenium.common.exceptions.WebDriverException: Message: chrome not reachable" local file

javascript - 构建 Promise 数组不起作用,但单个 Promise 可以