I'm writing a chrome extension which should be capable of running a script on that page as soon as it has been loaded. I implemented the feature to run the code on clicking on extension icon but when I added code to run that script on page load its not working
Manifest file
{
"name": "",
"description": "",
"version": "1.0",
"permissions": [
"activeTab",
"tabs"
],
"background": {
"scripts": ["background.js"],
"persistent": false
},
"browser_action": {
"default_title": "",
"default_icon": "6a00e3982283618833019affd3c028970c.png"
},
"manifest_version": 2
}
js file:
chrome.tabs.onUpdated.addListener(
function ( tabId, changeInfo, tab )
{
if ( changeInfo.status === "complete" )
{
chrome.tabs.executeScript({
code: "console.log('dsff');"
});
}
});
but despite this my js is not running when ever user changes the page in a tab
You can use the chrome. scripting API to inject JavaScript and CSS into websites. This is similar to what you can do with content scripts, but by using the chrome.
executeScript() Injects a script into a target context. The script is run at document_idle by default. Note: This method is available in Manifest V3 or higher in Chrome and Firefox 101. In Safari and Firefox 102+, this method is also available in Manifest V2.
This extension allows you to write, save, and execute javascript into web pages. You can save scripts to be run globally (on any page), on a specific domain, on a specific page, or via a "URL contains" string.
If you registered a callback to chrome.tabs.executeScript(...)
to catch any errors, e.g.:
chrome.tabs.executeScript({ code: "console.log('dsff');" }, function() {
if (chrome.runtime.lastError) {
console.log("ERROR: " + chrome.runtime.lastError.message);
}
});
you would notice the following error:
ERROR: Cannot access contents of url "...". Extension manifest must request permission to access this host.
So, you need to add the appropriate host match pattern to the permissions
list in your manifest. E.g. to be able to inject code into any http/https
page:
"permissions": ["*://*/*"]
Furthermore, if you omit the tabId
argument of chrome.tabs.executeScript(...)
it will apply to the currently active tab (which might defer from the one that fired the onUpdated
event). So, also, make the following change:
chrome.tabs.executeScript(tab.id, { code: "console.log('dsff');" }, function() {...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With