首页 > 解决方案 > How to set different styles for hundreds of different URLs in browser extension?

问题描述

I'm studying how to create browser extensions, using simple example from Mozilla site, which adds a red border to any pages loaded from "mozilla.org" or any of its subdomains. How to set different styles for hundreds of different URLs?

I tried to add new style to the manifest.json file and it works (see content_scripts section):

{

  "manifest_version": 2,
  "name": "Borderify",
  "version": "1.0",

  "description": "Adds a solid red border to all webpages matching mozilla.org.",
  "icons": {
    "48": "icons/border-48.png"
  },

  "applications": {
    "gecko": {
      "id": "borderify@mozilla.org",
      "strict_min_version": "45.0"
    }
  },

  "content_scripts": [
    {
      "matches": ["*://*.mozilla.org/*", "*://*.google.com/*"],
      "js": ["borderify.js"]
    },
    {
      "matches": ["*://*.opera.com/*", "*://*.stackoverflow.com/*"],
      "js": ["borderify_green.js"]
    }
  ]

}

Here files borderify.js and borderify_green.js contain the styles rules:

document.body.style.border = "5px solid red";

and

document.body.style.border = "5px solid green";

respectively.

But if I need to set different styles for hundreds of URLs? I guess that I cannot use manifest.json file for this purpose and need to set these styles in separate file.

How to set these styles for hundreds of URLs in a proper way?

标签: javascriptbrowser-extension

解决方案


在您的manifest.json中,查看content_scripts零件,尤其是其中的两个对象。

这些对象的matches属性告诉您的扩展您的代码应该执行哪些 URL。


在每个页面上执行特定代码:

因此,要在每个站点上执行您的代码(仅作为示例),请更改"*://*.mozilla.org/*", "*://*.google.com/*"]["*://*"].


*充当“任何” 。对于您的扩展,*://*.mozilla.org/*意味着:“在任何目录上的 mozilla.org 的任何 supdomain 上的任何协议上执行代码。”

*://*然后表示“在任何域上的任何协议上执行代码。

在不同的 URL 上执行不同的代码

恐怕在这种情况下,您需要手动将每个特定案例添加到清单中:

{
   "matches": ["*://*.mozilla.org/*"],
   "js": ["borderify.js"]
},
{
   "matches": ["*://*.opera.com/*"],
   "js": ["borderify_green.js"]
},
{ 
   "matches": ["*://*.somedomain.com/*"],
   "js": ["some_file.js"]
}

或者,您可以在每个页面上执行一些代码,检查您所在的页面并加载该页面的相关 .js 文件。


推荐阅读