我开发了一个 chrome 扩展,它工作得非常好。manifest.json
的一部分看起来像这样:
"content_scripts":[
{
"js":["js/script.js"],
"css": ["css/style.css"],
"matches": ["http://localhost/*", "https://localhost/*"]
}
],
因此扩展仅在域为
localhost
时才注入(inject)内容脚本,这也工作正常。现在我想要一种扩展弹出窗口可以有 的方法。 enable extension on this domain
或 disable extension on this domain
这样用户就可以根据需要启用/禁用扩展 .我已经在多个广告拦截器插件中看到了这一点,所以我想这应该是可能的。
最佳答案
这需要两个部分:
程序化脚本注入(inject)
现在有 contentScripts.register()
API ,它允许您以编程方式注册内容脚本。
browser.contentScripts.register({
matches: ['https://your-dynamic-domain.example.com/*'],
js: [{file: 'content.js'}]
});
此 API 仅在 Firefox 中可用,但有一个 Chrome polyfill您可以使用。 future 还会有chrome.scripting.registerContentScript
但它是 not yet implemented .获取新权限
通过使用
chrome.permissions.request
您可以添加可以注入(inject)内容脚本的新域。一个例子是:// 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 */
}
});
});
为此,您必须通过在 manifest.json
中添加它来允许按需添加新来源。{
"optional_permissions": [
"http://*/*",
"https://*/*"
]
}
还有一些工具可以为您和最终用户进一步简化此过程,例如
webext-domain-permission-toggle
and webext-dynamic-content-scripts
,许多与 GitHub 相关的扩展都使用它来添加对自托管 GitHub 安装的支持。他们还将在下次浏览器启动时注册您的脚本,并允许用户删除新的权限和脚本。
关于javascript - 以编程方式在 chrome 扩展中启用内容脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46476975/