window.onerror – getting insight into uncaught errors in your application.
To better understand what’s going on, consider the following example HTML document, served at http://example.com/test:
Here’s the contents of http://another-domain.com/app.js. It declares a single function,
foo, whose invocation will always throw a ReferenceError.
"Script error.", "", 0, 0, undefined
This isn’t a bug – browsers intentionally hide errors originating from script files from different origins for security reasons. It’s to avoid a script unintentionally leaking potentially sensitive information to an onerror callback that it doesn’t control. For this reason, browsers only give window.onerror insight into errors originating from the same domain. All we know is that an error occurred – nothing else!
In order to get visibility into errors thrown from scripts originating from different origins, you must do two things.
This tells the browser that the target file should be fetched “anonymously”. This means that no potentially user-identifying information like cookies or HTTP credentials will be transmitted by the browser to the server when requesting this file.
Cross Origin HTTP header
CORS is short for “Cross Origin Resource Sharing”, and it’s a set of APIs (mostly HTTP headers) that dictate how files ought to be downloaded and served across origins. By setting “Access-Control-Allow-Origin: *”, the server is indicating to browsers that any origin can fetch this file.
By setting the global wildcard, you are indicating that any origin can consume this server. If you want, you can restrict it to only known domains you control, e.g.
Access-Control-Allow-Origin: http://www.example.com, http://www.another-domain.com
Note: Most community CDNs properly set an Access-Control-Allow-Origin header.
Once both of these steps have been made, any errors triggered by this script will report to
window.onerror just like any regular same-domain script. So instead of “Script error”, the onerror example from the beginning will yield:
ReferenceError: bar is not defined", "http://another-domain.com/app.js", 2, 1, [Object Error]