如何仅在特定链接上运行background.js?

Mr.*_*r.X 2 javascript json google-chrome google-chrome-extension

我正在尝试编写一个 chrome 扩展,如果标签的链接包含特定的单词/字符串,则在加载标签时会关闭标签。matches我的目的是使用manifest.json. 不幸的是,这不起作用。我的manifest.json看起来像这样:

{
  "manifest_version": 2,
  "name": "Chrome Extension",
  "version": "0.1",
   "permissions": [
    "tabs"
  ],
  "content_scripts": [
    {
      "matches": [
       "<all_urls>"
      ],
      "js": ["content.js"]
    }
  ],
  "background": {
          "matches": [
               "https://www.google.de/",
                "https://sghm.eu/iserv/login"
          ],
          "scripts": ["background.js"],
          "persistent": true
  }
}
Run Code Online (Sandbox Code Playgroud)

我的background.js像这样:

chrome.tabs.onUpdated.addListener( function (tabId, changeInfo, tab) {
  if (changeInfo.status == 'complete') {
      console.log('background running');
      chrome.tabs.remove(tabId, function() { });
  }
})
Run Code Online (Sandbox Code Playgroud)

在我看来,我已经明确表示该脚本仅在google和上运行sghm.eu,那么为什么它在每个加载的页面上运行?

wOx*_*xOm 6

问题:

  • 正如您在文档中看到的那样,“背景”部分不能有“匹配” 。后台脚本在与选项卡无关的单独隐藏后台页面中运行。

  • 在manifest.json 中声明的内容脚本在所有URL 上运行。对于您想要实现的任务,您根本不需要内容脚本。

解决方案包括几个步骤:

  1. 删除“content_scripts”部分
  2. 从“背景”部分删除“匹配”
  3. 通过指定切换到事件页面脚本"persistent": false
  4. 在manifest.json中添加“webNavigation”权限并使用它来检测URL导航。

背景.js:

chrome.webNavigation.onCompleted.addListener(closeTab, {
  url: [
    {urlPrefix: 'https://www.google.de/'},
    {urlPrefix: 'https://sghm.eu/iserv/login'},
  ]
});

function closeTab(e) {
  if (!e.frameId) {
    chrome.tabs.remove(e.tabId);
  }
}
Run Code Online (Sandbox Code Playgroud)