简体   繁体   English

chrome扩展以在页面加载时运行脚本

[英]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. 我正在编写一个chrome扩展,它应该能够在加载后立即在该页面上运行脚本。 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: js文件:

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 但是,尽管如此,当用户在选项卡中更改页面时,我的js仍未运行

If you registered a callback to chrome.tabs.executeScript(...) to catch any errors, eg: 如果您注册了chrome.tabs.executeScript(...)的回调以捕获任何错误,例如:

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. 因此,您需要将相应的主机匹配模式添加到清单中的permissions列表中。 Eg to be able to inject code into any http/https page: 例如,为了能够将代码注入任何http/https页面:

"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). 此外,如果省略chrome.tabs.executeScript(...)tabId参数,它将应用于当前活动的选项卡(可能会推迟触发onUpdated事件的选项卡)。 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. 首先,为什么要为内容和后台脚本使用相同的文件(background.js)。

Content scripts can't use chrome.* api's 内容脚本不能使用chrome。* api

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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