Reputation: 973
In a Chrome extension, is there a way to globally trap/handle Javascript errors occurring in a content-script? (e.g. for submission to a Javascript error tracking service like bugsnag)
Ideally, I would setup a global window.onerror
handler at the top of the content script. But it's not working properly in Chrome 40: the error is caught, but the information supplied is useless: a message of 'Script error' and no url, lineNumber, column or error object with stack.
I created a test extension to show this busted behaviour for content scripts. Details below. Interesting findings:
window.onerror
works correctly in a background script, with full error informationwindow.onerror
on the hosting webpage can also see the error thrown by an extension content script (but the error doesn't contain any useful info either)In a new folder, create manifest.json
, content-script.js
and background-script.js
. Then load into Chrome via Window > Extensions > Load unpacked Extension.
{
"name": "Chrome extension content-script errors test",
"manifest_version": 2,
"version": "0.0.1",
"background": {
"scripts": [ "background-script.js" ]
},
"content_scripts": [{
"matches": ["<all_urls>"],
"js": ["content-script.js"]
}]
}
window.onerror = function (errorMsg, url, lineNumber, column, errorObj) {
console.log('Caught content script error');
console.log('errorMsg: ' + errorMsg);
console.log('url: ' + url);
console.log('lineNumber: ' + lineNumber);
console.log('column: ' + column);
console.log('errorObj follows:');
console.log(errorObj);
return true;
};
console.log('I am a content script, about to throw an error');
throw new Error('Is this error caught?');
window.onerror = function (errorMsg, url, lineNumber, column, errorObj) {
console.log('Caught background script error');
console.log('errorMsg: ' + errorMsg);
console.log('url: ' + url);
console.log('lineNumber: ' + column);
console.log('column: ' + column);
console.log('errorObj follows:');
console.log(errorObj);
return true;
};
//To see nice window.onerror behaviour for background script..
//Uncomment 2 lines below, reload extension, and look at extension console
//console.log('I am a background script, about to throw an error');
//throw new Error('Is this error caught?');
Upvotes: 46
Views: 13616
Reputation: 5305
See the most complete errors handling by Chrome extension content script in https://github.com/barbushin/javascript-errors-notifier/blob/master/content.js - it's source code of JavaScript Errors Notifier extension.
Upvotes: 0
Reputation: 973
5 months after asking this question, I'm now pretty convinced there isn't currently an easy way to global trap/handle Javascript errors occurring in a content script. As such,
Upvotes: 35
Reputation: 3601
Check out TraceKit, that's what we use at our company to do all front-end error logging. If you combine it with a javascript client library for your favorite logging service you're all set.
Upvotes: -1