javascript - 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?
解决方案
在您的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 文件。
推荐阅读
- c# - ASP.NET Core:带有 OpenID Connect 的注册按钮
- prolog - 从 XPCE 中的编辑器中读取文本
- python - Select 在来自每个客户端的几条消息后返回空套接字列表
- accumulo - 授予所有表的累积用户权限
- python - jsonResponse = r.json() NameError: name 'r' is not defined
- rest - 是否应该为 404 和 204 响应设置 Content-Type 标头?
- python - RuntimeWarning:从未等待协程'main'
- c - strlen 在循环中给出分段错误
- python - 如何设置可检查的菜单设置,真或假?如果是真的做某事
- itext - 使用 itextsharp 识别眼睛看不见但可以使用 Acrobat 搜索的文本