Josh Kelley Josh Kelley - 1 month ago 32
Javascript Question

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?

Answer

As best as I can tell, the cause is that "unhandledrejection" event handlers are silently ignored if they originate from a different script origin. (For more info, see MDN on same-origin policy.) Chrome is very strict with file URLs' security origins in particular, but I've found that unknowingly breaking the same origin policy can happen for other reasons too (such as developing in webpack-dev-server with Chrome Dev Tools open) this can happen surprisingly easily. See this Chrome issue for discussion.

A workaround is to test in a simpler, closer-to-production environment: running over a plain HTTP server (SimpleHTTPServer works well), with Dev Tools closed if necessary.