voi*_*oid 9 javascript google-chrome-extension
我开发了一个 chrome 扩展,它工作得非常好。
部分manifest.json看起来像这样:
"content_scripts":[
{
"js":["js/script.js"],
"css": ["css/style.css"],
"matches": ["http://localhost/*", "https://localhost/*"]
}
],
Run Code Online (Sandbox Code Playgroud)
因此扩展程序仅在域为 时才注入内容脚本localhost,这也工作正常。现在我想要一种方法,扩展弹出窗口可以有一个enable extension on this domain或disable extension on this domain,以便用户可以根据需要启用/禁用扩展。
我在多个广告拦截器插件中看到过,所以我想这应该是可能的。
这需要两部分:
现在有了chrome.scripting.registerContentScripts()API,它允许您以编程方式注册内容脚本。
chrome.scripting.registerContentScripts([{
id: "a-script",
matches: ['https://your-dynamic-domain.example.com/*'],
js: ['content.js']
}]);
Run Code Online (Sandbox Code Playgroud)
通过使用,chrome.permissions.request您可以添加可以注入内容脚本的新域。一个例子是:
// In a content script, options page or popup
document.querySelector('button').addEventListener('click', () => {
chrome.permissions.request({
origins: ['https://your-dynamic-domain.example.com/*']
}, granted => {
if (granted) {
/* Use contentScripts.register */
}
});
});
Run Code Online (Sandbox Code Playgroud)
为此,您必须通过将其添加到您的manifest.json
{
"optional_permissions": [
"http://*/*",
"https://*/*"
]
}
Run Code Online (Sandbox Code Playgroud)
还有一些工具可以为您和最终用户进一步简化此操作,例如
webext-domain-permission-toggle和webext-dynamic-content-scripts,许多 GitHub 相关扩展都使用它们来添加对自托管 GitHub 安装的支持。
他们还将在下一次浏览器启动时注册您的脚本,并允许用户删除新的权限和脚本。