在特定网站上运行 Chrome 扩展

Mat*_*tti 2 javascript google-chrome-extension

我正在编写一个优惠券样式的 Chrome 扩展,我希望它仅在特定网站(超过 300 个网站)上运行。我读过有关在 content_scripts 中指定网站 url 的内容,但这似乎不实用,尤其是当我需要更新它时。这是我的脚本:

清单.json

{
      "name": "Example",
      "description": "description",
      "version": "1.0",
      "manifest_version": 2,

      "background": 
      {
        "scripts": ["js/background.js", "js/eventPage.js", "js/jquery- 
         3.2.1.min.js"],
        "persistent":false
      },

      "page_action": {
        "default_icon":"img/32icon.png"
      },

      "content_scripts": [
        {
        "matches": ["https://*/*"],
        "js": ["js/sites_cs.js", "js/jquery-3.2.1.min.js"]
        }
      ],

       "permissions": [
       "tabs",
       "http://*/*",
       "https://*/*",
       "activeTab"
     ]
    }
Run Code Online (Sandbox Code Playgroud)

Ivá*_*oko 6

您可以拥有一个包含要匹配的 URL 的数组,并以编程方式仅将内容脚本注入到匹配的网页。例如,删除filecontent_scripts的条目manifest.json并将此代码包含在后台脚本中:

背景.js

// myURLs contains the websites where you want your content script to run
const myURLs = ['www.example1.com','www.anotherone.com','www.athird.one'];

chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
    if (changeInfo.status == 'complete' && myURLs.some(url => tab.url.includes(url))) {
        chrome.tabs.executeScript(tabId,{file:'js/jquery-3.2.1.min.js'},()=>{
            chrome.tabs.executeScript(tabId,{file:'js/sites_cs.js'});
        });
    }
});
Run Code Online (Sandbox Code Playgroud)

这样,您只需使用myURLs所需的 URL 更新变量,您的内容脚本将仅注入到这些站点上。