What the Heck Does “Script Error” Mean?

Share this article

What the Heck Does “Script Error” Mean?

This article was created in partnership with Sentry.io. Thank you for supporting the partners who make SitePoint possible.

If you’ve done any work with the JavaScript onerror event before, you’ve probably come across the following:

Script error.

“Script error” is what browsers send to the onerror callback when an error originates from a JavaScript file served from a different origin (different domain, port, or protocol). It’s painful because, even though there’s an error occurring, you don’t know what the error is, nor from which code it’s originating. And that’s the whole purpose of window.onerror — getting insight into uncaught errors in your application.

The Cause: Cross-origin Scripts

To better understand what’s going on, consider the following example HTML document, hypothetically served from http://example.com/test:

<!doctype html>
<html>
<head>
  <title>example.com/test</title>
</head>
<body>
  <script src="http://another-domain.com/app.js"></script>
  <script>
  window.onerror = function (message, url, line, column, error) {
    console.log(message, url, line, column, error);
  }
  foo(); // call function declared in app.js
  </script>
</body>
</html>

Here’s the contents of http://another-domain.com/app.js. It declares a single function, foo, whose invocation will always throw a ReferenceError.

// another-domain.com/app.js
function foo() {
  bar(); // ReferenceError: bar is not a function
}

When this document is loaded in the browser, and JavaScript is executed, the following is output to the console (logged via the window.onerror callback):

"Script error.", "", 0, 0, undefined

This isn’t a JavaScript 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!

I’m Not a Bad Person, Really!

Despite browsers’ good intentions, there are some really good reasons why you want insight into errors thrown from scripts served from different origins:

  1. Your application JavaScript files are served from a different hostname (e.g., static.sentry.io/app.js).
  2. You are using libraries served from a community CDN, like cdnjs or Google’s Hosted Libraries.
  3. You’re working with a commercial third-party JavaScript library that is only served from external servers.

But don’t worry! Getting insight into a JavaScript error served by these files only requires a few simple tweaks.

The Fix: CORS Attributes & Headers

In order to get visibility into a JavaScript exception thrown by scripts originating from different origins, you must do two things.

1. Add a crossorigin="anonymous" script attribute

<script src="http://another-domain.com/app.js" crossorigin="anonymous"></script>

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.

2. Add a Cross Origin HTTP header**

Access-Control-Allow-Origin: \*

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. Alternatively, you can restrict it to only a known origin you control:

$ curl --head https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.js | \
    grep -i "access-control-allow-origin"

Access-Control-Allow-Origin: *

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 would yield:

"ReferenceError: bar is not defined", "http://another-domain.com/app.js", 2, 1, [Object Error]

Boom! You’re done — “Script error” will plague you and your team no more.

An Alternative Solution: try/catch

Sometimes we’re not in a position to adjust the HTTP headers of scripts our web application is consuming. In those situations, there’s an alternative approach: using try/catch.

Consider the original example again, this time with try/catch:

<!-- note: crossorigin="anonymous" intentionally absent -->
<script src="http://another-domain.com/app.js"></script>
<script>
window.onerror = function (message, url, line, column, error) {
  console.log(message, url, line, column, error);
}

try {
  foo(); // call function declared in app.js
} catch (e) {
  console.log(e);
  throw e; // intentionally re-throw (caught by window.onerror)
}
</script>

For posterity, some-domain.com/app.js once again looks like this:

// another-domain.com/app.js
function foo() {
  bar(); // ReferenceError: bar is not a function
}

Running the example HTML will output the following two entries to the console:

=> ReferenceError: bar is not defined
     at foo (http://another-domain.com/b.js:2:3)
     at http://example.com/test/:15:3

=> "Script error.", "", 0, 0, undefined

The first console statement — from try/catch — managed to get an error object complete with type, message, and stack trace, including file names and line numbers. The second console statement from window.onerror, once again, can only output “Script error.”

Now, does this mean you need to try/catch all of your code? Probably not. If you can easily change your HTML and specify CORS headers on your CDNs, it’s preferable to do so and stick to window.onerror.

But, if you don’t control those resources, using try/catch to wrap third-party code is a surefire (albeit tedious) way to get insight into errors thrown by cross-origin scripts.

Note: by default, raven.js, Sentry’s JavaScript SDK, carefully instruments built-in methods to try to automatically wrap your code in try/catch blocks. It does this to attempt to capture error messages and stack traces from all your scripts, regardless of which origin they’re served from. It’s still recommended to set CORS attributes and headers if possible.

Of course, there are plenty of commercial and open-source tools that do all the heavy-lifting of client-side reporting for you. (Psst: you might want to try Sentry to debug JavaScript.)

That’s it! Happy error monitoring.

Frequently Asked Questions (FAQs) about Script Errors

What are the common causes of script errors?

Script errors are often caused by issues within the code of a web page or application. These can include syntax errors, where the code is written incorrectly, or logical errors, where the code is correct but doesn’t perform as expected. Other common causes include browser incompatibility, where the script doesn’t work correctly on certain browsers, and issues with third-party scripts, such as plugins or extensions, that interfere with the script’s execution.

How can I prevent script errors?

Preventing script errors involves careful coding and thorough testing. Use a good code editor that can highlight syntax errors and provide code suggestions. Always test your scripts on multiple browsers and devices to ensure compatibility. Also, keep your scripts up-to-date and check regularly for updates or patches for any third-party scripts you’re using.

What does “Uncaught ReferenceError” mean?

An “Uncaught ReferenceError” is a type of script error that occurs when a script tries to use a variable that hasn’t been declared. This can happen if you misspell a variable name, try to use a variable outside of its scope, or forget to declare a variable before using it.

How can I debug script errors?

Debugging script errors involves identifying the problem, isolating the cause, and then fixing the issue. Use your browser’s developer tools to inspect the error message and find out where in the code the error occurred. Then, check the problematic code for any syntax or logical errors. If the error is caused by a third-party script, you may need to contact the script’s developer for assistance.

Can script errors harm my computer?

In general, script errors are more annoying than harmful. They can cause web pages or applications to behave unexpectedly or stop working, but they don’t typically pose a threat to your computer. However, some malicious scripts can cause harm, such as those used in phishing attacks or to deliver malware. Always be cautious when downloading scripts from untrusted sources.

Why do I keep getting script errors in my browser?

If you’re frequently encountering script errors in your browser, it could be due to several reasons. Your browser might be outdated, or there could be issues with your browser’s settings or extensions. It’s also possible that the websites you’re visiting contain poorly written or incompatible scripts.

How can I fix a script error on my website?

Fixing a script error on your website involves identifying the error, finding the problematic script, and then correcting the issue. Use your browser’s developer tools to inspect the error message and locate the error in your code. Then, check the script for any syntax or logical errors and correct them.

What does “Script Error” mean in Google Analytics?

In Google Analytics, a “Script Error” typically means that an error occurred in a script on your website, but the specifics of the error couldn’t be captured. This can happen if the error originates from a script hosted on a different domain, due to same-origin policy restrictions.

How can I handle script errors in JavaScript?

JavaScript provides several methods for handling errors, including try-catch blocks, which allow you to “catch” errors and handle them gracefully. You can also use the “onerror” event handler to capture and handle errors globally.

Can script errors affect SEO?

While script errors themselves don’t directly affect SEO, they can impact user experience, which is a factor in search engine rankings. If script errors cause your website to load slowly, crash, or behave unpredictably, it can lead to a higher bounce rate, which can negatively impact your site’s SEO.

Ben VinegarBen Vinegar
View Author

Ben is VP Engineering at Sentry, where he oversees an organization of 40 engineers. Together, the team has upgraded the front-end, added support for mobile platforms, and scaled Sentry's hosted product to support over 100,000 active users and more than 9,000 paying customers. He is also the author of Third-Party JavaScript and a speaker on browser-side technologies. Previously, Ben led teams at Shape Security, Disqus, and FreshBooks.

error monitoringjoelfsentrysponsored
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week