Javascript Chrome 扩展:让它在每个页面加载时运行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6497548/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:02:42  来源:igfitidea点击:

Chrome Extension: Make it run every page load

javascriptgoogle-chromegoogle-chrome-extension

提问by albertosh

I want to make a chrome extension that executes some scripts after one page is loaded, I am not sure whether I have to implement this logic on the background page or it can be anywhere else, any help here will be greatly appreciated.

我想制作一个在页面加载后执行一些脚本的 chrome 扩展,我不确定我是否必须在后台页面上实现这个逻辑,或者它可以在其他任何地方,这里的任何帮助将不胜感激。

回答by fiatjaf

From a background scriptyou can listen to the chrome.tabs.onUpdatedevent and check the property changeInfo.statuson the callback. It can be loadingor complete. If it is complete, do the action.

后台脚本中,您可以侦听chrome.tabs.onUpdated事件并检查changeInfo.status回调的属性。它可以是正在加载已完成。如果已完成,请执行操作。

Example:

例子:

chrome.tabs.onUpdated.addListener( function (tabId, changeInfo, tab) {
  if (changeInfo.status == 'complete') {

    // do your things

  }
})

Because this will probably trigger on every tab completion, you can also check if the tab is activeon its homonymous attribute, like this:

因为这可能会在每个选项卡完成时触发,您还可以检查选项卡是否active在其同名属性上,如下所示:

chrome.tabs.onUpdated.addListener( function (tabId, changeInfo, tab) {
  if (changeInfo.status == 'complete' && tab.active) {

    // do your things

  }
})

回答by Matchu

If it needs to run on the onloadevent of the page, meaning that the document and all its assets have loaded, this needs to be in a content scriptembedded in each page for which you wish to track onload.

如果它需要onload在页面事件上运行,这意味着文档及其所有资产都已加载,则这需要嵌入在您希望跟踪的每个页面中的内容脚本onload

回答by Bohdan

You can put your script into a content-script, see

您可以将脚本放入内容脚本中,请参阅

回答by Evan Ross

This code should do it:

这段代码应该这样做:

manifest.json

清单文件

   {
      "name": "Alert 'hello world!' on page opening",
      "version": "1.0",
      "manifest_version": 2,
      "content_scripts": [
        {
          "matches": [
            "<all_urls>"
          ],
          "js": ["content.js"]
        }
      ]
    }

content.js

内容.js

alert('Hello world!')