Search code examples
javascriptgoogle-chrome-extension

JavaScript class override for all frames


If an injected JavaScript code modifies Date class

Date = new Proxy(Date, { ...

or

Date.prototype.toString = function() { ...

on the top level of the window/document, would those override changes apply also to all frames and iframes recursively?

If not, is there a way to force it?


Solution

  • No, and there's no way to do it automatically without modifying the source code of the browser.

    You'll have to run your code in every frame explicitly by using one of these methods:

    1. Declare a content script that runs in every frame:

      "content_scripts": [{
        "matches": ["<all_urls>"],
        "js": ["content.js"],
        "run_at": "document_start",
        "all_frames": true,
        "match_about_blank": true
      }],
      
    2. Or add allFrames: true, matchAboutBlank: true to options of chrome.tabs.executeScript.

    3. Or use the nuclear option: chrome.debugger API to attach to the tab and send a CDP command like Page.addScriptToEvaluateOnNewDocument. The downside is that it shows a warning notification on top of every tab.

    In cases 1 and 2 the code that overrides the prototypes should be added in page context. Also note that Chrome/Firefox may be unable to run content scripts in certain iframes due to bugs or inherent restrictions, for example iframes with CSP sandbox in Firefox or iframes with src="javascript:..." in Chrome.