223

I have a script that detects Javascript errors on my website and sends them to my backend for reporting. It reports the first error encountered, the supposed line number, and the time.

EDIT to include doctype:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" xmlns:fb="http://www.facebook.com/2008/fbml">

...

<script type="text/javascript">
//<![CDATA[
// for debugging javascript!
(function(window){
    window.onerror = function(msg, url, ln) {
        //transform errors
        if (typeof(msg) === 'object' && msg.srcElement && msg.target) {
            if(msg.srcElement == '[object HTMLScriptElement]' && msg.target == '[object HTMLScriptElement]'){
                msg = 'Error loading script';
            }else{
                msg = 'Event Error - target:' + msg.target + ' srcElement:' + msg.srcElement;
            }
        }

        msg = msg.toString();

        //ignore errors
        if(msg.indexOf("Location.toString") > -1){
            return;
        }
        if(msg.indexOf("Error loading script") > -1){
            return;
        }

        //report errors
        window.onerror = function(){};
        (new Image()).src = "/jserror.php?msg=" + encodeURIComponent(msg) + "&url=" + encodeURIComponent(url || document.location.toString().replace(/#.*$/, "")) + "&ln=" + parseInt(ln || 0) + "&r=" + (+new Date());
    };
})(window);
//]]>
</script>

Because of this script, I'm acutely aware of any javascript errors that are happening on my site. One of by biggest offenders is "Script Error." on line 0. in Chrome 10+, and Firefox 3+. This error doesn't exist (or may be called something else?) in Internet Explorer.

Correction (5/23/2013): This "Script Error, Line 0" error is now showing up in IE7 and possibly other versions of IE. Possibly a result of a recent IE security patch as this behavior previously did not exist.

Does anyone have any idea what this error means or what causes it? It happens on about 0.25% of my overall pageloads, and represents half the reported errors.

10
  • What is your doctype? If you're not declaring an XHTML doctype, then you don't need CDATA, which could be why there are script errors.
    – James
    May 6, 2011 at 16:05
  • I appreciate the help... Added the doctype: XHTML. Also, though, only happening on 0.25% of pageloads... I would think it's something more exotic. May 6, 2011 at 16:09
  • 3
    @jayp: Just mentioning. XHTML doctype is still HTML parser. You have to sent content as application/xhtml+xml to run it in XHTML parser (like XHTML specification says). There is whole a lot of content which claims to be XHTML, but sends normal HTML doctype. Because of how incorrectly content creators use XHTML, browsers decided to only use XML parser on application/xhtml+xml (it's really strict parser). The hixie.ch/advocacy/xhtml and webdevout.net/articles/beware-of-xhtml says why not use HTML parser with XHTML.
    – 0..
    May 6, 2011 at 16:23
  • 12
    Sigh... for the love of god, anyone reading this, please make your error messages explain exactly what went wrong! By saving yourself 30 seconds of effort writing it, you’re wasting the world man-years! Mar 15, 2012 at 12:56
  • 1
    You are ignoring Error Loading Script Errors. Why? Are they safe to ignore ?
    – rampr
    May 4, 2012 at 10:28

13 Answers 13

282

The "Script error." happens in Firefox, Safari, and Chrome when an exception violates the browser's same-origin policy - i.e. when the error occurs in a script that's hosted on a domain other than the domain of the current page.

This behavior is intentional, to prevent scripts from leaking information to external domains. For an example of why this is necessary, imagine accidentally visiting evilsite.com, that serves up a page with <script src="yourbank.com/index.html">. (yes, we're pointing that script tag at html, not JS). This will result in a script error, but the error is interesting because it can tell us if you're logged in or not. If you're logged in, the error might be 'Welcome Fred...' is undefined, whereas if you're not it might be 'Please Login ...' is undefined. Something along those lines.

If evilsite.com does this for the top 20 or so bank institutions, they'd have a pretty good idea of which banking sites you visit, and could provide a much more targeted phishing page. (This is just one example, of course. But it illustrates why browsers shouldn't allow any data to cross domain boundaries.)

I've tested this in the latest versions of Safari, Chrome, and Firefox - they all do this. IE9 does not - it treats x-origin exceptions the same as same-origin ones. (And Opera doesn't support onerror.)

From the horses mouth: WebKit source that checks origin when passing exceptions to onerror(). And the Firefox source that checks.

UPDATE (10/21/11): The Firefox bug that tracks this issue includes a link to the blog post that inspired this behavior.

UPDATE (12/2/14): You can now enable full cross-domain error reporting on some browsers by specifying a crossorigin attribute on script tags and having the server send the appropriate CORS HTTP response headers.

10
  • 3
    Thanks for this. I'd like a bit of clarification. I see detailed error messages from scripts that I include on my page all the time. For example, if I include jQuery from google's cdn and use it to manipulate a non existent element on my page, I get an onerror that points to google's CDN. Are you saying that "Script Error." is happening because the remote script is throwing the exception? Oct 29, 2011 at 17:27
  • 181
    You would have thought someone would have had the sense to say "A remote script has thrown an error that was hidden due to the same-origin policy", instead of leave you wondering what went wrong, eh?... Mar 15, 2012 at 12:59
  • 4
    @broofa Does this mean I'll get better exceptinos if I host jquery on my domain instead of using Google's CDN? Apr 13, 2012 at 7:24
  • 6
    Small update. It also happens locally when a page is loaded via file:// and the script is run through eval(). Minor use-case but still :) Sep 5, 2012 at 9:52
  • 8
    After some investigation I noticed that a Script Error. also occurs if the user has installed a Safari Extension (probably the same for Firefox Plug-Ins) that injects JavaScript code with errors Mar 31, 2015 at 6:32
54

An update for those that will stumble into this question in the future : broofa is right with the answer and there's no workaround for this.

Obviously other stumbled into this limitation and some bugs requesting for an fix were filed for Firefox : Bug 69301 and for WebKit : Bug 70574

The good news is that the bug has been resolved for Firefox with the release of Firefox 13. This is how you use it :

<script src="http://somremotesite.example/script.js" crossorigin>

crossorigin is equivalent to crossorigin=anonymous and tells the browser to do a CORS fetch of the script without sending credentials.

You must ensure that the script is sent with an Access-Control-Allow-Origin HTTP header value that matches the requesting domain, e.g.,

Access-Control-Allow-Origin: http://myhomesite.example
Access-Control-Allow-Origin: *

otherwise the browser will cancel loading the script.

For Apache:

Header set Access-Control-Allow-Origin "*"

(And see CORS examples for other web servers.)

If you're sending scripts in PHP:

header('Access-Control-Allow-Origin', 'http://myhomesite.example');

I've tested this and it works as expected. all errors from the script.js will be caught by the window.onerror handler with message, file and line details.

The WebKit bug hasn't been fixed yet, but a patch has been proposed (and uses the same solution). Hopefully the fix will be released soon.

More info about CORS here : http://enable-cors.org/

3
  • 3
    Good summary: blog.errorception.com/2012/12/…
    – sam
    Mar 26, 2013 at 20:10
  • 1
    Re webkit. If you mean this one, it looks like it's resolved now: bugs.webkit.org/show_bug.cgi?id=70574
    – UpTheCreek
    Jun 19, 2013 at 9:46
  • 3
    Let's say we want to monitor JS errors in mysite.com/index.php, which includes a JS file from an external party (e.g. an API provider's server apiprovider.com/api.js); in this case we don't have access to that server so we cannot add the "Access-Control-Allow-Origin" header. Is there any way to get error messages originated from api.js?
    – Eugenio
    Apr 4, 2014 at 9:47
29

This one took quite a bit to figure out.

We did a bunch of stuff to try and solve it, including doing things like dumping the WHOLE document body back to our servers via Ajax to try and figure it out.

I am still unsure what causes "Script Error." (with the period BTW, that's how it shows up in our Ajax logger) in Firefox, but in Chrome, we were able to narrow it down to...

Drum roll...

The auto translate feature of Google Chrome.

Many English speaking people probably do not even know about this feature, but to test it, I guess visit a non-English site using Chrome. Or better yet, if you dig thru the Chrome options, there's a spot to change the browser language. Change it to something non-English, restart the browser, and visit an English site.

You should get the bar at the top asking if you would like Chrome to translate the page for you.

In our case anyways, the translator was causing the issue since it injects a script tag into your document body and (guessing here) uses some sort of JS-based system to send the content to Google's servers and get them to translate it.

Even though the error in the console was Unreferenced something, the message that was being sent to window.onerror was "Script Error.".

Anyways, there is a cure.

http://googlewebmastercentral.blogspot.com/2007/12/answering-more-popular-picks-meta-tags.html

<meta name="google" content="notranslate"/>

This will do 2 things (as far as we know, maybe more?):

a) Disable the translate bar from popping up in Chrome.

b) Disable translating of the the page via translate.google.com.

In our situation anyways, this solved A TON of these "Script Error." issues we were experiencing.

Excuse the spelling mistakes in this post, I am still on a non-English mode in Chrome writing this, and the spell checker is not set to English ;) Time to switch back.

Enjoy!

1
  • 4
    The direct reason is probably that the translator script was run from a different domain then the web page, and onerror (at least in Firefox) just says "Script error" in such a case.
    – Tgr
    Oct 11, 2011 at 11:03
10
+300

Due to the low %, you can assume they're not normal users. Probably users with userscripts, bookmarklets or even maybe just messing with the console on you website. Having the whole HTML of a page where it happens could help testing this theory. As well as the complete error. It should give you a url, is it always the same? Is the line really 0 or just undefined?

I don't think setting default values in you onerror is a good idea and the 0 probably comes from parseInt(ln || 0) when the error isn't really on the page (see examples above).

Adding a if to see if the line is known either in the JavaScript to ignore those errors (because they probably don't come from your own code) or in the server-side code to take care of them separately would, imo, be better.

=== EDIT === Got to: http://www.xavierm02.net/AZE/ Install the user.js file (I did it on Chrome but it should work on Firefox too). Then open the html page on the same browser. It'll show you the error (I only changed that insteal of reporting to the server, it writes it on the page). With 0 as line number.

7
  • The URL is evenly distribute amongst the pages of my site. I'm guessing bookmarklets or even extensions or themes too, considering it's FF and chrome. However, I'd love to be able to repro this error message exactly before safely ignoring it. May 10, 2011 at 23:20
  • Replace your line with (new Image()).src = "/jserror.php?msg=" + encodeURIComponent(msg) + "&url=" + encodeURIComponent(url) + "&ln=" + parseInt(ln) + "&r=" + (+new Date());and you'll probably see no url (because it's an extension or something local so the browser doesn't show you) and no line number.
    – xavierm02
    May 11, 2011 at 7:09
  • And btw, you should rather get the timestamp with your server rather than with JS (and even maybe just getting the version, instead of the timestamp).
    – xavierm02
    May 11, 2011 at 7:10
  • 1
    In fact, JS should just send the raw data and PHP should take care of ignoring the load errors and so on.
    – xavierm02
    May 11, 2011 at 7:22
  • I do some processing on the JS side because I only want to report the FIRST relevant error, so I reassign the onerror function back to nothing after a real error comes in. This also prevents errors that are happening in loops from ddos'ing my server. May 11, 2011 at 17:51
3

I had a similar problem: my scripts are served by a subdomain and fall under the same origin restriction. However, I solved this by:

1) adding every script tag like this:

<script type="text/javascript" src="http://subdomain.mydomain.tld" crossorigin="*.mydomain.tld" />

2) modifying the apache httpd.conf by adding the following inside every vhost (you must enbable mod_headers):

<IfModule mod_headers.c>
Header add Access-Control-Allow-Origin "*.mydomain.tld"
</IfModule>

Hope this helps ...

EDIT

On one of my server I was not able to make this functional except by replacing

*.mydomain.tld

by

*

Be aware of the flaws with potentially allowing * to phish extended information. Documentation on CORS, same-origin, img & fonts, cdn is available but very fewer about script tag crossorigin details is available.

1
2

A good article which finally point to this thread. https://danlimerick.wordpress.com/2014/01/18/how-to-catch-javascript-errors-with-window-onerror-even-on-chrome-and-firefox/

1

In Chrome, I also get "Script error" (on line 0) when loading both the HTML and Javascript from file:// . This doesn't happen in Firefox. Probably overzealous same-origin protection of Chrome.

All is good when loading the same HTML and Javascript over HTTP.

0

How about the below. The script error is not available via JavaScript so just isolate that particular case and handle it as best you can.

window.onerror = function (msg, url, lineNo, columnNo, error) {
    var string = msg.toLowerCase();
    var substring = "script error";
    if (string.indexOf(substring) > -1){
        alert('Script Error: See Browser Console for Detail');
    } else {
        alert(msg, url, lineNo, columnNo, error);
    }
  return false;
};
2
  • how do you log this on karma? May 23, 2018 at 11:26
  • Are you telling that browser console has the details, but onerror does not? Nov 7, 2019 at 12:11
0

Both Chrome and Firefox on iOS are based on the Safari Webview but insert a bunch of custom scripts into each page that is loaded. If in any of those scripts something goes wrong, it gets reported s Script error on line 0 as well. (Browser inserted scripts count as cross origin as well)

As I have tracked down and documented in this other SO thread both Chrome and Firefox on iOS have issues in their custom scripts handling SVG elements correctly. So in addition to all other answers in this thread: If you use SVG elements and <a> tags inside <svg> tags on your page, that will lead to Script errors being reported in iOS Chrome and iOS Firefox.

-1

I'll tell you what fixed it for me on Safari (WebKit): If I put the JS callback routine actually on the page, then I get full info. If I include it in a .js file via a tag, I just get the "Script error" error (with no linenumber, etc.).

Maybe this is related to what Broofa said.

Anwyay, so now I have a small callback in the page, and then the rest of the file outside of the page.

0
-3

I've done a bit of searching and it appears that a "Script Error" means it had trouble loading a file that it was asked to look for. This could be a caching problem on the client side, or it could be a server problem due to overloading.

It's most likely caused by something like this where the script itself is the file it can't load, hence the error occurring on line 0.

<script type="text/javascript" src="somescript.js"></script>
3
  • Good thought, but we explicitly ignore when a script fails to load. We've detected that error specifically and ignore it. May 6, 2011 at 16:32
  • 1
    How did you detect when a script fails to load? I remember having trouble with that at one point. script.onerror wasn't getting fired for missing scripts in some browsers. May 11, 2011 at 16:29
  • "Source error." (little-e) appears in both webkit and FF sources. See my answer above. fwiw.
    – broofa
    Oct 16, 2011 at 12:38
-3

I've experienced

Script Error. line 0

errors for some time being reported back to our server when the error occurred in customer browsers. Yesterday for the first time (after introducing "use strict"; in our javascript) I was able to replicate this issue in Safari and Chrome on Windows 7. After littering our code with alert() statements I traced this error down to the use of an undefined variable! e.g. xx = 123; where xx is not defined with a var statement.

Safari reported this as

ReferenceError: Strict mode forbids implicit creation of global property 'xx'

within Web Inspector, but window.onerror function was detecting

Script Error. line 0

-11

Grepping Firefox's source code reveals that there's no "Script Error.". Thus, it's very likely that some script on your site is throwing an uncaught error like this:

throw new Error('Script Error.');

Probably this statement is only reached in Firefox and Chrome.

Not sure why there's no line number though. Maybe some eval() issue?

4
  • 1
    I've tried throwing this exactly as you've recommended. It doesn't report "Script Error.". It reports "Thrown Exception not caught: Script Error.". Good thought though. May 10, 2011 at 23:17
  • It might also be one of the extensions installed by the user that is causing the error. May 11, 2011 at 16:27
  • 1
    No way. You'll see "Script Error" all over the web if you look in the right plaes.
    – Alkanshel
    Aug 24, 2012 at 21:52
  • 3
    Uh, no. It's actually "Script error." with a small "e". That's why I didn't find it in the source code. Aug 26, 2012 at 19:31

Not the answer you're looking for? Browse other questions tagged or ask your own question.