Search code examples
javascripthtmlgoogle-chromegoogle-chrome-extensioncontent-script

Chrome extension content script access to extension frame


I'm looking for a way to send data (or straightly edit) the DOM/HTML from the original popup page, from inside a content script. My script is started using the following line:

chrome.tabs.executeScript(null, {file: "script.js"});

I'm looking for a way to access the original popup's HTML so I can write and update a log of what that script.js is doing dynamically.

If you need more information, I'll be more than happy to edit this post.

Thanks a lot for your help!


Solution

  • There is a security separation between extension contexts and content script contexts. You can't just reference window of the popup from a content script (unlike getBackgroundPage() or getViews() from extension context, which is a hack to begin with).

    The proper way to communicate between the two would be Messaging (you can send messages from the content script via runtime.sendMessage, and popup will be among the receivers).

    Important to remember that popup can close, and then its state will be lost and it won't be listening. In that case, you either want to use a background script as a "proxy" between the two, or employ some persistent storage like chrome.storage.

    Finally, Messaging/Storage only supports JSON-serializable payloads. This means you can't send DOM nodes across, among other things. You need to communicate only the bare minimum data required for your purposes and construct the DOM on the popup side.