Search code examples
google-chromegoogle-chrome-extensionchrome-extension-manifest-v3

How to executeScript for webRequest event onBeforeRequest in Google Chrome Extension


Following Chrome Extension Manifest V3 rule I want to create an extension, that listens to particular network request and, for startes, just log them to the console of the currently opened tab (later I want to add custom script and styles to the page in the current tab).

For this I try to utilize chrome.scripting.executeScript.

When I implement the sample from https://github.com/GoogleChrome/chrome-extensions-samples/blob/main/examples/page-redder/manifest.json it works like expected for the chrome.action.onClicked listener.

As soon as I try to execute a script within the chrome.webRequest.onBeforeRequest listener, this error pops up:

Error in event handler: TypeError: Error in invocation of scripting.executeScript(scripting.ScriptInjection injection, optional function callback): Error at parameter 'injection': Error at property 'target': Missing required property 'tabId'. at chrome.webRequest.onBeforeRequest.addListener.urls ()

Missing required property tabId? I assume it has to do with the lifecycle, but I cannot figure out what to do. This is my manifest:

{
    "name": "Getting Started Example",
    "description": "Build an Extension!",
    "version": "1.0",
    "manifest_version": 3,
    "background": {
        "service_worker": "background.js",
        "matches":   [ "<all_urls>"]
    },
    "host_permissions": [
        "<all_urls>"
    ],
    "permissions": [
        "activeTab",
        "tabs",
        "webRequest",
        "webNavigation",
        "management",
        "scripting"
      ]
  }

And this is my script, I just slightly modified the "redden"-example:

function reddenPage(url) {
    console.log(url);
}
  
chrome.webRequest.onBeforeRequest.addListener((tab) => {
    chrome.scripting.executeScript({
      target: { tabId: tab.id },
      function: reddenPage,
      args: [tab.url],
    });
},
  {urls: ["*://*.google.com/*"]},
    []);  

Solution

  • I don't know exactly why, but the script from Github seems not work. This is how it works:

    It's not only a couple of changed brackets, look at tab instead of (tab), but also tab.tabId instead of tab.id:

    chrome.webRequest.onBeforeRequest.addListener(tab => {
        chrome.scripting.executeScript(
            {
            target: { tabId: tab.tabId },
            function: reddenPage,
            args: [details.url],
            },
            () => { console.log('ZZZ') });
        },  {
            urls: ['<all_urls>']
        });