为chrome扩展中的内容脚本动态配置exclude_matches

Elv*_*uza 1 google-chrome google-chrome-extension

对于chrome扩展中的内容脚本,您可以指定matchesexclude_matches控制它们注入的页面.这必须在扩展名的清单中指定,如下所示

{
  "name": "Color picker",
  ...
  "content_scripts": [
    {
      "matches": ["http://*/*", "https://*/*"],
      "exclude_matches": ["http://www.google.com/*"],
      "css": ["color_picker.css"],
      "js": ["jquery.js", "color_picker.js"]
    }
  ],
  ...
}
Run Code Online (Sandbox Code Playgroud)

我想知道如果我可以添加["http://www.yahoo.com/*"],exclude_matches作为当分机正在使用中.这样,我就可以让用户控制了exclude_matches

Rob*_*b W 8

扩展程序无法修改任何本地文件,包括扩展名manifest.json.Chrome提供了可选权限的API ,但不包括内容脚本.

您可以手动创建灵活的模式:

// In the content script:
var exclude = /^https?:\/\/(www\.)?yahoo\.com\//;
if (!exclude.test(location.href)) {
     // Run logic.
}
Run Code Online (Sandbox Code Playgroud)

正则表达式非常强大,但并非必要.而不是location.href其他location属性,例如location.host可以使用.

另见:MDN :window.location .