Search code examples
javascriptgoogle-chrome-extension

Executing script to modify tab html from service worker


I'm trying to intercept a GET request using a service worker and print the GET request's output onto the current page, however I can't execute any Javascript on the page...

Here's the extension code I've used (Generalized to work on all URLs)

manifest.json

{
  "name": "Getting Started Example",
  "description": "Build an Extension!",
  "version": "1.0",
  "manifest_version": 2,

  "permissions": [
    "webRequest",
    "<all_urls>",
    "activeTab",
    "*://*/*",
    "tabs"
  ],
  
  "background": {
    "service_worker": "background.js"
  }
}

background.js

chrome.webRequest.onBeforeRequest.addListener(
    function(details)
    {
    chrome.tabs.query(
        { currentWindow: true }, 
        function(tabs) 
        {
            chrome.tabs.executeScript(tabs[0].id, 
            {
                code: 'alert("yo")'
            }, function() { });
        });
     return {cancel: false};
  },
  {urls: ["<all_urls>"]},
);

I keep getting the error Unchecked runtime.lastError: Cannot access contents of url "chrome://extensions/". Extension manifest must request permission to access this host. (Even though I allowed permission on all URLs and on the active tab??)


Solution

  • No need for activeTab permission as it won't give you access to the chrome:// pages anyway (these are protected browser UI pages), its purpose is different, more in the documentation.

    No need for chrome.tabs.query either. You probably want to run the code in the tab that made the request in which case just use details.tabId, see more info in the documentation.

    No need for service_worker as it won't wake up for webRequest events, which is a known bug in Chrome. Just use the standard ManifestV2 scripts.

      "background": {
        "scripts": ["background.js"]
      }
    

    Also you may want to limit the types of requests to just xhr:

    chrome.webRequest.onBeforeRequest.addListener(details => {
      chrome.tabs.executeScript(details.tabId, {
        frameId: details.frameId,
        code: 'console.log(' + JSON.stringify(details) + ')',
      }, () => chrome.runtime.lastError); // suppressing errors
    }, {
      urls: ['<all_urls>'],
      types: ['xmlhttprequest'],
    });