1

I have a Chrome Manifest V3 web extension that needs to inject javascript into a webpage on page load of every page (not fussy as to exactly when the javascript is run).

This is so that javascript on the webpage can optionally call the function defined by the web extension.

According to the docs at https://developer.chrome.com/docs/extensions/reference/scripting/, the chrome.scripting.executeScript will do what I need:

You can use the chrome.scripting API to inject JavaScript and CSS into websites.

The chrome.scripting.executeScript function takes a tabId as a mandatory parameter, but nothing in the docs indicates where to get the tabId from. The docs make reference to an unspecified function getTabId(), but otherwise say nothing.

In addition, the docs do not say where the chrome.scripting.executeScript function is to be run. In the content script? In theory that won't work as the tab ID is not accessible. In the background service worker? What happens if the service worker is not running when the page is loaded?

Note that the following questions are not related to this question:

Graham Leggett
  • 911
  • 7
  • 20
  • The "unrelated" [answer](https://stackoverflow.com/a/9517879) describes how to do it correctly, including MV3-compatible methods. Which method to choose depends on the specifics of your use case. If you really want to use executeScript you would use chrome.tabs.onUpdated or chrome.webNavigation event in a service worker and specify `world: 'MAIN'` in the parameters to expose the injected JS thing to the web page. – wOxxOm Sep 16 '22 at 14:36
  • @w0xx0m Alas the answer you cite had been found, tried, and didn't help in this case. Method 4 refers to incomplete documentation, I raised a bug to fix it at https://bugs.chromium.org/p/chromium/issues/detail?id=1364596. Next bug: "Uncaught (in promise) Error: Cannot access a chrome:// URL" – Graham Leggett Sep 17 '22 at 08:38
  • Those are definitely correct methods, so there might have been a mistake in your code. Note that you can't inject in `chrome://` URLs by default, there's a way to do it via a command line switch though. Also, the most efficient method is registerContentScripts in a background script. I'll probably add an example later. – wOxxOm Sep 17 '22 at 13:04
  • Here's an [existing example](https://stackoverflow.com/a/72607832). If you only want it on a certain site then change `matches` [accordingly](https://developer.chrome.com/extensions/match_patterns). – wOxxOm Sep 17 '22 at 14:21

1 Answers1

0

To get the tabId --

In Manifest V3, you pass it as a value.

chrome.action.onClicked.addListener((tab) => {
  if(!tab.url.includes("chrome://")) {
    chrome.scripting.executeScript({
      target: { tabId: tab.id },
      function: reddenPage
    });
  }
});

Check out Google's Chrome Extension example "Page Redder" for the full code

RockyK
  • 403
  • 9
  • 12