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

后端 未结 2 1083
予麋鹿
予麋鹿 2020-12-05 20:40

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 gett

2条回答
  •  甜味超标
    2020-12-05 21:34

    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:

    • https://stackoverflow.com/a/9517879/1507998
    • https://stackoverflow.com/a/9636008/1507998

提交回复
热议问题