Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

chrome extension to run script on page load

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

like image 675
Minhaz Avatar asked Nov 23 '13 22:11

Minhaz


People also ask

Can you run scripts on Chrome?

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.

What is Chrome scripting executeScript?

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.

What is inject JS in Chrome?

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.


1 Answers

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() {...
like image 151
gkalpak Avatar answered Oct 16 '22 16:10

gkalpak