Documentation Menu

Prevent Obfuscated Script Errors

Cross domain exceptions get obfuscated

Jsnlog.js uses an window.onerror handler to handle any JavaScript errors that haven't been caught elsewhere in your code (details).

When an uncaught exception happens, the browser calls this handler, passing in the line number, stack trace, etc. of the exception.

However, if the exception happened in a script that was loaded from a different domain, such as a CDN, the browser calls the handler without the exception information. Instead, it sets the error message to a meaningless "Script error." This way, by default the script doesn't leak potentially sensitive information to the onerror callback.

Obfuscation can happen even if your code is all on the one domain

This will obviously affect you if some of your scripts sit on a different domain. But it also affects you if you load libraries such as jQuery from a different domain, such as a CDN. Take this code:

<!-- Load jQuery from a different domain -->
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>

<script>
$(function() {
    throw "This exception will be obfuscated";
});
</script>

Here your throw statement sits on your page, so it definitely doesn't get loaded from a different domain. Still, the exception gets obfuscated. Why? Because your code is executed by a jQuery method and jQuery was loaded from a different domain.

Solution: Enable sharing of exception information

To enable sharing of exception information, these things need to be done:

  1. Add crossorigin="anonymous" to your cross domain script tags
  2. Add a Cross Origin HTTP header to the script responses

Add crossorigin="anonymous" to your cross domain script tags

<script crossorigin="anonymous" src="https://code.jquery.com/jquery-2.2.4.min.js"></script>

crossorigin is an HTML5 attribute used with a few tags that load static content, such as script.

Setting crossorigin to anonymous ensures that no user credentials will be sent to the server as part of the request for the file.

Add a Cross Origin HTTP header to the script responses

When the server responds with the script file, it has to include an Access-Control-Allow-Origin HTTP header that shows pages from your domain can load this file. For example:

Access-Control-Allow-Origin: *

Most CDNs set this header, including the jQuery CDN shown above and cdnjs, which hosts JSNLog.