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

后端 未结 2 1085
予麋鹿
予麋鹿 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:43

    The problem

    The main problem is JS context isolation, i.e. the fact that "Content scripts execute in a special environment called an isolated world". This is a good thing, of course, because it avoids conflicts and enhances security, but yet a problem if you want to catch errors.

    Each isolated world sees its own version of the (window) object. Assigning to the object affects your independent copy of the object...

    ...neither one can read the other's event handler. The event handlers are called in the order in which they were assigned.


    A solution

    On posiible solution (a.k.a. hack) consists of the following steps:

    1. Inject some code into the web-page itself (and try to make is as non-obtrusive as possible to avoid conflicts).
    2. In that code register an event listener for errors and store the error data in a DOM-node's dataset.
    3. Finally, from within the content script, use a MutationObserver to watch for changes in this DOM-node's attributes.
    4. Once a change in the specified data-<...> attribute is detected, grab its new value and there you have your error info right in your content script :)

    The source code

    Below is the source code of a sample extension that does exactly that.

    manifest.json:

    {
        "manifest_version": 2,
    
        "name":    "Test Extension",
        "version": "0.0",
    
        "content_scripts": [{
            "matches":    ["*://*/*"],
            "js":         ["content.js"],
            "run_at":     "document_start",
            "all_frames": true
        }],
    }
    

    content.js:

    /* This 
    
                                     
                  
提交回复
热议问题