我正在尝试在Google Chrome中使用一个简单的
unhandledrejection处理程序.
如果我将以下代码粘贴到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标准的“未捕获(在承诺中)”控制台错误,但没有消息框.
index.html的:
- <!doctype html>
- <html>
- <body>
- <script type="text/javascript" src="app.js"></script>
- </body>
- </html>
app.js:
- window.addEventListener('unhandledrejection',2000);
- });
这是怎么回事?
解决方法
据我所知,原因是如果“unhandledrejection”事件处理程序源自不同的脚本原点,则会被忽略. (有关详细信息,请参阅
same-origin policy上的MDN.)Chrome是
very strict,特别是文件URL的安全来源,但我发现在不知情的情况下也会因其他原因而违反相同的原始策略(例如在webpack-dev-中开发)打开Chrome开发工具的服务器).有关讨论,请参阅
this Chrome issue.
解决方法是在更简单,更接近生产环境中进行测试:在普通HTTP服务器上运行(SimpleHTTPServer运行良好),必要时关闭Dev Tools.