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:
- How would I inject code from my Chrome extension into a webpage? (closed, no reference to Manifest v3)
- Use a content script to access the page context variables and functions (opposite question)
- How to access the webpage DOM rather than the extension page DOM? (nothing to do with the DOM)