javascript – unhandledrejection无法在Chrome中运行

前端之家收集整理的这篇文章主要介绍了javascript – unhandledrejection无法在Chrome中运行前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试在Google Chrome中使用一个简单的 unhandledrejection处理程序.

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

  1. window.addEventListener('unhandledrejection',function(e) {
  2. console.log(e);
  3. alert(e.reason);
  4. });
  5. new Promise(function(resolve,reject) {
  6. setTimeout(function() {
  7. return reject('oh noes');
  8. },2000);
  9. });

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

  1. <!doctype html>
  2. <html>
  3. <body>
  4. <script type="text/javascript">
  5. window.addEventListener('unhandledrejection',function(e) {
  6. console.log(e);
  7. alert(e.reason);
  8. });
  9. new Promise(function(resolve,reject) {
  10. setTimeout(function() {
  11. return reject('oh noes');
  12. },2000);
  13. });
  14. </script>
  15. </body>
  16. </html>

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

index.html的:

  1. <!doctype html>
  2. <html>
  3. <body>
  4. <script type="text/javascript" src="app.js"></script>
  5. </body>
  6. </html>

app.js:

  1. window.addEventListener('unhandledrejection',2000);
  2. });

这是怎么回事?

解决方法

据我所知,原因是如果“unhandledrejection”事件处理程序源自不同的脚本原点,则会被忽略. (有关详细信息,请参阅 same-origin policy上的MDN.)Chrome是 very strict,特别是文件URL的安全来源,但我发现在不知情的情况下也会因其他原因而违反相同的原始策略(例如在webpack-dev-中开发)打开Chrome开发工具的服务器).有关讨论,请参阅 this Chrome issue.

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

猜你在找的JavaScript相关文章