简体   繁体   中英

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

If you registered a callback to chrome.tabs.executeScript(...) to catch any errors, eg:

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. Eg 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() {...

First, why are you using same file (background.js) for both content and background script.

Content scripts can't use chrome.* api's

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM