Chrome Extension: How do I inject a script that the user provided?

Executing arbitrary user code (userscripts) isn’t yet implemented in ManifestV3 and is still forbidden by the policies of Chrome’s Web store for extensions.

The personal workaround (e.g. in an unpacked extension) is to run such code in the page context i.e. not as a content script:

async function execInPage(code) {
  const [tab] = await chrome.tabs.query({currentWindow: true, active: true});
  chrome.scripting.executeScript({
    target: {tabId: tab.id},
    func: code => {
      const el = document.createElement('script');
      el.textContent = code;
      document.documentElement.appendChild(el);
      el.remove();
    },
    args: [code],
    world: 'MAIN',
    //injectImmediately: true, // Chrome 102+
  });
}

execInPage('console.log(123)');

Warning! This may be blocked by the site if it has a strict Content-Security-Policy, in which case you can remove this header via declarativeNetRequest API.

Leave a Comment