81

I'm writing a Chrome extension and trying to overlay a <div> over the current webpage as soon as a button is clicked in the popup.html file.

When I access the document.body.insertBefore method from within popup.html it overlays the <div> on the popup, rather than the current webpage.

Do I have to use messaging between background.html and popup.html in order to access the web page's DOM? I would like to do everything in popup.html, and to use jQuery too, if possible.

wOxxOm
  • 65,848
  • 11
  • 132
  • 136
Steven
  • 1,231
  • 1
  • 12
  • 11

2 Answers2

136

Problem: extension pages (popup, options, background page in MV2, etc.) are separate from the web page and they have their own DOM, document, window, and a chrome-extension:// URL.

  • Note that service worker doesn't have any DOM/document/window at all.
  • To inspect each context of the extension use its own devtools.

Solution: use a content script to access the web page or interact with its contents.

  • Content scripts execute in the web page, not in the extension.
  • Content scripts are isolated by default, see how to run code in page context (aka MAIN world).
  • Don't load your content scripts in the extension page.

Method 1. Declarative

manifest.json:

"content_scripts": [{
  "matches": ["*://*.example.com/*"],
  "js": ["contentScript.js"]
}],

It will run once when the page loads. After that happens, use messaging .

Warning! It can't send DOM elements, Map, Set, ArrayBuffer, classes, functions, and so on. It can only send JSON-compatible simple objects and types so you'll need to manually extract the required data and pass it as a simple array or object.

Method 2. Programmatic

  • ManifestV3:

    Use chrome.scripting.executeScript in the extension script (like the popup) to inject a content script/function into a tab on demand.

    The result of this method is the last expression in the content script so it can be used to extract data. Data must be JSON-compatible, see the warning above.

    Required permissions in manifest.json:

    • "scripting" - mandatory;
    • "activeTab" - ideal scenario, suitable for a response to a user action (usually a click on the extension icon in the toolbar). Doesn't show any permission warning when installing the extension.

    If ideal scenario is impossible add the allowed sites to host_permissions in manifest.json:

    • "*://*.example.com/" plus any other sites you want.

    • "<all_urls>" or "*://*/" these will put your extension in a super slow review queue in the Chrome Web Store because of broad host permissions.

  • ManifestV2 differences to the above:

wOxxOm
  • 65,848
  • 11
  • 132
  • 136
Mohamed Mansour
  • 39,445
  • 10
  • 116
  • 90
11

Some examples of the extension popup script that use programmatic injection to add that div.

ManifestV3

Don't forget to add the permissions in manifest.json, see the other answer for more info.

  • Simple call:

    (async () => {
      const [tab] = await chrome.tabs.query({active: true, currentWindow: true});
      await chrome.scripting.executeScript({
        target: {tabId: tab.id},
        func: inContent1,
      });
    })();
    
    // executeScript runs this code inside the tab
    function inContent1() {
      const el = document.createElement('div');
      el.style.cssText = 'position:fixed; top:0; left:0; right:0; background:red';
      el.textContent = 'DIV';
      document.body.appendChild(el);
    }
    

    Note: in Chrome 91 or older func: should be function:.

  • Calling with parameters and receiving a result

    Requires Chrome 92 as it implemented args.

    Example 1:

    res = await chrome.scripting.executeScript({
      target: {tabId: tab.id},
      func: (a, b) => { return [window[a], window[b]]; },
      args: ['foo', 'bar'],
    });
    

    Example 2:

    (async () => {
      const [tab] = await chrome.tabs.query({active: true, currentWindow: true});
      let res;
      try {
        res = await chrome.scripting.executeScript({
          target: {tabId: tab.id},
          func: inContent2,
          args: [{ foo: 'bar' }], // arguments must be JSON-serializable
        });
      } catch (e) {
        console.warn(e.message || e);
        return;
      }
      // res[0] contains results for the main page of the tab 
      document.body.textContent = JSON.stringify(res[0].result);
    })();
    
    // executeScript runs this code inside the tab
    function inContent2(params) {
      const el = document.createElement('div');
      el.style.cssText = 'position:fixed; top:0; left:0; right:0; background:red';
      el.textContent = params.foo;
      document.body.appendChild(el);
      return {
        success: true,
        html: document.body.innerHTML,
      };
    }
    

ManifestV2

  • Simple call:

    // uses inContent1 from ManifestV3 example above
    chrome.tabs.executeScript({ code: `(${ inContent1 })()` });
    
  • Calling with parameters and receiving a result:

    // uses inContent2 from ManifestV3 example above
    chrome.tabs.executeScript({
      code: `(${ inContent2 })(${ JSON.stringify({ foo: 'bar' }) })`
    }, ([result] = []) => {
      if (!chrome.runtime.lastError) {
        console.log(result); // shown in devtools of the popup window
      }
    });
    

    This example uses automatic conversion of inContent function's code to string, the benefit here is that IDE can apply syntax highlight and linting. The obvious drawback is that the browser wastes time to parse the code, but usually it's less than 1 millisecond thus negligible.

wOxxOm
  • 65,848
  • 11
  • 132
  • 136