GET net::ERR_FAILED error when probing for extension - javascript

There is a certain Chrome extension and I want to get a PNG file from it by XMLHttpRequest. If the extension is enabled, I want to write 'load' to the console, and if the extension is disabled, I want to write 'error' to the console.
It works fine, but if the Extension is disabled, Chrome writes an error in the console that I do not want to appear:
How can I remove this error from the console?
(I have tried window.onerror but it doesn't work)
The code:
var loadHref = function(href) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function(){console.log('load')};
xmlhttp.onerror = function() {console.log('error');};
xmlhttp.open('GET', href);
xmlhttp.send();
}
loadHref('chrome-extension://77672b238520494cba8855547dd00ba8/img/icon24.png');

Basically, you can't silence those errors, as they are not JS errors but network errors.
Assuming your goal is to detect that a specific extension is present:
Assume you need it at a specific domain and for a specific extension that is controlled by you.
In this case, the optimal approach is externally_connectable communication. Here's a sample.
Assume you need it at a non-specific domain not known in advance, but you control the extension.
In this case, a Content Script can be injected (probably with "run_at": "document_start") and add something to the document signalling the presence of the extension. For example, injecting a page-level script that sets a variable.
Assume you don't control the extension.
Well, in that case you're screwed. If an extension won't cooperate in the manners described above, probing its web-accessible resources (if any!) is the only way to detect it, short of watching for specific content script activity in the DOM (again, if any).

Actually, there is already an existing issue on error when chrome cast extension is not installed with google-cast-sdk and based on that issues tracker, this hasn't been totally resolved yet. There are, however, given workarounds from one of the comments:
the workarounds would be to either install the Google Cast extension or disable network warnings (please note you may miss some warnings that could be on interest to you) so you don't see these additional logs.
And, you may also try with the probable solutions given in this SO post - Google chrome cast sender error if chrome cast extension is not installed or using incognito and who knows, it might help. :)

Related

Retrieving console errors to html

My question is different from the other posts similar to this.
AutoCAD offers developers a means of displaying a URL page inside the application. I created an intranet site for my company with the hopes that users can explore via desktop browser or their AutoCAD application.
The problem is that the browser AutoCAD uses is Chrome version 33 (currently its at 84) - there is no way to update or change the browser either.
I have no way to "inspect" or debug the site inside AutoCAD - and I've come to find out there are many difference in v84 and v33. I'm trying to diagnose errors right now but again, I have no way of accessing the console logs inside the AutoCAD Browser.
Is there a way for me to "alert" any errors that the console is trying to give me? (ie: the page can't find a script reference, there is an unexpected '.', etc...)
NOTE - my site runs great on the most updated Chrome browser (v84 on desktop browser), but some little things are not working right in v33 (in AutoCAD Browser).
If you control the website you can attach a listener on the window to listen for any unhandled exceptions. Add this before all other scripts to make sure everything is captured.
window.on('error', (e) => {
// if error is intresting, do work.
alert(e.message);
});
The handler accepts an ErrorEvent object.
NOTE - This will not capture errors that are triggered in scripts across domain. For example if you are loading google maps, and an error is triggered within that script, you will typically get a 'Script error.' and no other info. This has to do with cross origin policies. You can read more here.
If you need to specifically to capture data sent to console.error you can simply proxy the function. This may not capture anything except for code that explicitly calls console.error and is not recommended.
const error = console.error;
console.error = (...args) => {
// alert(...);
error.apply(console, args);
}

QUnit super unhelpful error message [duplicate]

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.
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.
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/
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!
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.
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.
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/
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.
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;
};
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.
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.
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>
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
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?

How can I detect if javascript files are being blocked by IE11 security settings?

I have a site that renders nearly everything through javascript (not my design), and this has caused a lot of issues in Internet Explorer, of course. The recurring issue is that when the user has security set to High, the necessary javascript files get blocked, I believe because they are from another domain. This has something to do with the Drupal setup, I'm not entirely sure, but the important thing to know is that the files are served from a different domain and there's nothing I can do about that.
What my client wants is for an alert to pop up whenever these scripts are getting blocked that tells their users how to change their security settings.
1) If I add a javascript file on the same domain, it shouldn't get blocked, right?
2) Is there a way I can detect what the user's security settings are, or detect if scripts are being blocked using javascript?
There is another way to detecting whether a js script was loaded or not; there could be so many things, it can be their network firewall, os level firewall, browser security settings, the list continues with possibilities.
You can have:
<script src="http://yourdomain.com/the_js_script.js"></script>
<script>if (typeof foo == "undefined") {alert ('error loading script');}</script>
Make sure in the_js_script.js, you'd have
var foo = 'Script loaded successfully';
You can do that for all the js scripts, and alert distinct messages so the user at least knows which scripts were blocked or if they came through.
Setting your IE security set to High, disables all scripts from running in the browser.
The only workaround available is to place a warning message using the noscript html tag.
<noscript>Your browser does not support JavaScript!</noscript>
I would have liked to comment on #unixmiah's answer, but I don't have enough reputation, and I believe this is an answer as well. Unixmiah's solution won't work to alert blocked clients, I think since the alert needs a script to be generated.However, I believe this would work (wouldn't it?):
jQuery(function($) {
$(document).ready(function() {
$("p#jstrap").hide();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="jstrap">You seem to have switched Javascript off.</p>

Log JavaScript console into a log file with Firefox

We have a web application which runs in a kiosk mode Firefox, using the RKiosk extension to achieve this. We suspect that we have a very rare error in the system which yields in a JavaScript error. However because we can't access the JavaScript console we can't examine the log.
I'm searching for an option to make Firefox log all JavaScript console messages into a file regardless of the tab and page opened. I can't seem to find any extension for this. I'm already using log4javascript which sends errors back to the server, but it seems that our application crashes in a way that it skips the logging altogether.
Writing to a file sounds like a tedious task to me. It requires privileges that browser code doesn't normally have and you'd have to negotiate with an add-on you'd have to write in order to access file I/O.
From what I understand your issue is
I'd like to make Firefox log all errors
There are several approaches we can do to tackle this
First approach - log everything to localStorage too:
Now, rather than writing to an actual file, you can write to localStorage or IndexedDB instead.
localStorage["myApplog"] = localStorage["myApplog"] || "";
var oldLog = console.log;
console.log = function(){
oldLog.apply(console,arguments); // use the old console log
var message = "\n "+(new Date).toISOString() + " :: "+
Array.prototype.join.call(arguments," , "); // the arguments
localStorage["myApplog"] += message;
}
This is rather dirty and rather slow, but it should get the job done and you can access the log later in local storage. LocalStorage has a ~5MB limit if I recall correctly which I think is enough if you don't go crazy with logging. You can also run it selectively.
Second approach - log only errors
This is similar to what Pumbaa80 suggested. You can simply override window.onerror and only log errors.
// put an empty string in loggedWinErrors first
var oldError = window.onerror || function(){};
window.onerror = function(err,url,lineNumber){
oldError.call(this,err,url,lineNumber);
var err ="\n Error: (file: " + url+", error: "+err+", lineNumber: "+lineNumber+")");
localStorage["loggedWinErrors"] += err;
}
Third and drastic approach - use a VM.
This is the most powerful version, but it provides the most problematic user experience. You run the kiosk in a virtual machine, you detect an uncaught exception - when you do you freeze the machine and save its state, and run a backup VM instead. I've only had to do this when tackling the most fearsome errors and it's not pretty. Unless you really want the whole captured state - don't do this.
Really, do the extension before this - this is tedious but it gets very solid results.
In conclusion, I think the first approach or even just the second one are more than enough for what you need. localStorage is an abstracted storage that web pages get for saving state without security issues. If that's not big enough we can talk about an IndexedDB solution.
It all really depends on the use case you have.
You can use XULRunner...a Mozilla runtime environment for XUL applications. It uses Gecko like Firefox and:
You can access the file system or using the SQLite database to store logs.
You can render your kiosk in fullscreen mode without using extensions.
Have you tried jserrorcollector? We are using it and it works fine (only in Firefox). It's only for Java.
// Initialize
FirefoxProfile ffProfile = null;
ffProfile = new FirefoxProfile();
JavaScriptError.addExtension(ffProfile);
// Get the errors
List<JavaScriptError> jsErrors = JavaScriptError.readErrors(webDriver);
More information: https://github.com/mguillem/JSErrorCollector
Have you considered remote logging?
I commonly assign window.onerror to do send a request to a webserver storing the details of the error remotely. You could do the same with console.log if you preferred.
Try the following console export. It is a plugin for Firebug of Firefox. It's quite handy.
http://www.softwareishard.com/blog/consoleexport/
If you are able/willing to switch from Firefox to Chrome or Opera you would be able to use the Sandboxed Filesystem API to write a local file. See:
http://www.html5rocks.com/en/tutorials/file/filesystem/
http://caniuse.com/filesystem
Start in kiosk mode using chrome.exe --kiosk <url>
You would then want to disable Alt-F4 and Ctrl-Alt-Del which on Windows can be done with several third-party tools like Auto Hotkey (Disable Ctrl-Alt-Del Script).
You could use a remote logging script like Qbaka. It catches every JS error and sends it to the Qbaka server. There you can login and see all JS errors. Qbaka stores the exact error message, the script, line number, stack trace and the used browser for each error message.

Cryptic "Script Error." reported in Javascript in Chrome and Firefox

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.
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.
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/
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!
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.
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.
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/
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.
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;
};
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.
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.
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>
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
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?

Categories

Resources