Cross-domain Script Errors

Conrad Irwin in Engineering on August 11th, 2014

If you’ve ever come across a “Script Error” on line 0, you’ve run afoul of the Same Origin Policy. This happens when there’s an error during the first pass of a cross-domain script.

The browser obscures the real error message to close a security vulnerability that can be used to read information from other sites the user may be logged into. Debugging script errors can be tricky because although the developer console contains the correct error message and line number, both window.onerror and Bugsnag can only show you “Script Error.”

I’ve detailed the fix below, which is to enable CORS on your web-server. But first here’s a summary of the when errors are visible.

Summary of when error messages are visible

Browsers disagree on which errors should be obscured, and which should be visible. Firefox takes the view that only SyntaxErrors are a problem, whereas Chrome and Safari take a more conservative view. In those browsers any Error that happens when running the script is also obscured.

Syntax Errors
(no CORS)
Runtime Errors
(no CORS)
Syntax Errors
(CORS)
Runtime Errors
(CORS)
Firefox
Chrome
Safari
IE <=10✔*
IE >=11

* This is a security vulnerability.

The Fix

Enabling CORS for script tags requires two steps.

  1. Configure your web-server to send the CORS header.

    Access-Control-Allow-Origin: *

  2. Add the “crossorigin” attribute to your script tag.

    <script type="text/javascript" src="//cdn.example.com/site.js" crossorigin>

With these changes, Bugsnag will report errors that happen in your script at load time even if you host your Javascript on a CDN. And it will also continue to report all other errors, including stacktraces in every browser, completely automatically.

Bugsnag has world-leading support for automatically monitoring Javascript errors. This lets you find out as soon as something goes wrong, so you can fix problems before too many people are affected. Sign up for a free trial now.