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

Javascript 如何仅在特定链接上运行background.js?,javascript,json,google-chrome,google-chrome-extension,Javascript,Json,Google Chrome,Google Chrome Extension,我正在尝试编写一个chrome扩展,当标签被加载时,如果它们的链接包含特定的单词/字符串,它会关闭标签。我的意图是使用manifest.json中的匹配语句来解决这个问题。不幸的是,这不起作用。我的manifest.json如下所示: { "manifest_version": 2, "name": "Chrome Extension", "version": "0.1", "permissions": [ "tabs" ], "content_scripts"

我正在尝试编写一个chrome扩展,当标签被加载时,如果它们的链接包含特定的单词/字符串,它会关闭标签。我的意图是使用
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
  }
}
chrome.tabs.onUpdated.addListener( function (tabId, changeInfo, tab) {
  if (changeInfo.status == 'complete') {
      console.log('background running');
      chrome.tabs.remove(tabId, function() { });
  }
})
在我看来,我已经明确表示脚本只在
google
sghm.eu
上运行,那么为什么它会在每个加载的页面上运行呢?

问题:

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

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

解决方案包括几个步骤:

  • 删除“内容脚本”部分
  • 从“背景”部分删除“匹配项”
  • 通过指定
    “persistent”:false切换到事件页面脚本
  • 在manifest.json中添加权限,并使用它检测URL导航
  • background.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);
      }
    }
    
    问题:

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

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

    解决方案包括几个步骤:

  • 删除“内容脚本”部分
  • 从“背景”部分删除“匹配项”
  • 通过指定
    “persistent”:false切换到事件页面脚本
  • 在manifest.json中添加权限,并使用它检测URL导航
  • background.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);
      }
    }