Monday, May 20, 2024
21
rated 0 times [  28] [ 7]  / answers: 1 / hits: 6704  / 11 Years ago, mon, december 2, 2013, 12:00:00

There is a Google Chrome extension with content script that handles JS errors occured on all tabs pages. But the problem is that no one of usual methods of getting errors stack trace does not work.



For example, there is a code in content script of Chrome extension:



window.addEventListener('error', function(event) {
console.log(event.error.stack); // event.error will be null
}, false);


If I call this code inside web page, so event.error will contains Error object with stack property.



Same problem with trying to get stack trace using:



console.log((new Error()).stack));


Does anybody knows some working issue to get error stack trace inside content script of Chrome extension?



Error stack trace must be received as string or Array, means not just like some output in JS console by calling console.trace().



How to reproduce:




  1. Download https://mega.co.nz/#!ENw00YAC!92gBZEoLCO9jPsWyKht4dbjYyo0Zk-PU5YAj0h88-3Q

  2. Unpack jzen.zip to some /jsen folder

  3. Open chrome://extensions in your Google Chrome, enable Developer mode http://i.imgur.com/5x5D6NP.png

  4. Click Load unpacked extension button and select path to /jsen folder

  5. Open /jsen/content.js file and add console.log('JSEN', e.error.stack); inside window.addEventListener('error', function(e) {

  6. Go to http://xpart.ru/_share/js.htm and see result in JS console(Ctrl+Shift+J)

  7. Try to edit /jsen/content.js to get correct error trace

  8. To reinitialize Chrome extension source code click http://i.imgur.com/SjFgkHA.png


More From » google-chrome

 Answers
9

As you mention, the error property of the event object is null when capturing the event in Content Script context, but it has the required info when captured in webpage context. So the solution is to capture the event in webpage context and use messaging to deliver it to the Content Script.



// This code will be injected to run in webpage context
function codeToInject() {
window.addEventListener('error', function(e) {
var error = {
stack: e.error.stack
// Add here any other properties you need, like e.filename, etc...
};
document.dispatchEvent(new CustomEvent('ReportError', {detail:error}));
});
}

document.addEventListener('ReportError', function(e) {
console.log('CONTENT SCRIPT', e.detail.stack);
});

//Inject code
var script = document.createElement('script');
script.textContent = '(' + codeToInject + '())';
(document.head||document.documentElement).appendChild(script);
script.parentNode.removeChild(script);


The techniques used are described in:




[#49932] Saturday, November 30, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kaleyv

Total Points: 259
Total Questions: 99
Total Answers: 107

Location: Saint Helena
Member since Tue, Nov 3, 2020
4 Years ago
;