How to get errors stack trace in Chrome extension content script?

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:

Leave a Comment