Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unhandledrejection not working in Chrome

I'm trying to get a simple unhandledrejection handler working in Google Chrome.

If I paste the following code into a JSFiddle and run it in Chrome, I get an error box, as expected:

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

If I create an HTML file with an embedded script and load it in Chrome as a file:/// URL, I get a message box, as expected.

<!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>

If I create separate HTML and JS files and load it in Chrome as a file:/// URL, I get Chrome's standard 'Uncaught (in promise)' console error but no message box.

index.html:

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

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);
});

What's going on?

like image 506
Josh Kelley Avatar asked Oct 13 '16 16:10

Josh Kelley


1 Answers

This can be solved by adding crossorigin="anonymous" to the script that is causing unhandled rejection.

<script src="non-default-domain.js" type="text/javascript" crossorigin="anonymous"></script>

like image 127
haael Avatar answered Oct 12 '22 22:10

haael