What the heck is “Script error?”

综合技术 2018-06-23 阅读原文

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:


  window.onerror = function (message, url, line, column, error) {
    console.log(message, url, line, column, error);
  foo(); // call function declared in app.js

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

"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 and 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

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:

Access-Control-Allow-Origin: https://www.example.com

Note: most community CDNs properly set an Access-Control-Allow-Origin header:

$ 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:

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) {
  throw e; // intentionally re-throw (caught by window.onerror)

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.




Top 15 resources for learning JavaScript HTML, cascading stylesheets (CSS), and JavaScript have experienced massive growth and evolution over the past two decades, which should come as no su...
Why does jqplot behave this way? I have a chart that consists of 4 series. Three of the four are stacked bar charts and the forth is a line. Why is the graph acting this way? I assum...
JavaScript——基本语法 单词掌握 BOM浏览器对象模型DOM文档对象模型document文档 break中断continue继续 1.js脚本位置 通常可以在三个地方编写js脚本代码,一是在网页文件的标签对中直接编写,二是将js代码放置在一个单独的文件中(.js后缀文件),三是将脚本程序代码作为某个HTML...
给你的博客园图片添加标题 一直以来都觉得在图片下面添加一个标题可以更加清晰的表示这张图片的含义,可是博客园原生并不支持这种渲染方式,再加上博客园可以自己写js来更改主题,于是通过搜索资料完成给博客园图片添加标题的功能。 当我们如下书写markdown时: ![](https://images.morethink...
Messing with MessageChannel We're getting close to being able to ship a beta release of our work porting Brackets to the browser. I'll spend a bunch of time blogging about it...