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