以编程方式在Chrome扩展程序中启用内容脚本 [英] Enable content script in chrome extension programmatically

查看:52
本文介绍了以编程方式在Chrome扩展程序中启用内容脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经开发了chrome扩展程序,它的工作原理绝对不错.

I have developed a chrome extension and it is working absolutely fine.

manifest.json 的一部分看起来像这样:

Part of the manifest.json looks like this:

"content_scripts":[
        {
            "js":["js/script.js"],
            "css": ["css/style.css"],
            "matches": ["http://localhost/*", "https://localhost/*"]
        }
    ],

因此扩展名仅在域为 localhost 时才注入内容脚本,这也可以正常工作.现在,我想要一种扩展名弹出窗口可以具有在该域上 启用扩展名 在该域上禁用扩展名 ,以便用户可以根据需要启用/禁用扩展名.

so the extension injects the content script only when the domain is localhost, which is also working fine. Now I want a way by which the extension popup can have a enable extension on this domain or disable extension on this domain in the so the user can enable/disable the extension according to needs.

我已经在多个广告拦截器插件中看到了这一点,所以我认为应该有可能.

I have seen that in multiple ad-blocker plugins, so I guess it should be possible.

推荐答案

这需要两个部分:

现在有 <代码> contentScripts.register() API ,可让您以编程方式注册内容脚本.

Now there's the contentScripts.register() API, which lets you programmatically register content scripts.

browser.contentScripts.register({
    matches: ['https://your-dynamic-domain.example.com/*'],
    js: [{file: 'content.js'}]
});

此API仅在Firefox中可用,但是您有 Chrome polyfill 可以使用.

This API is only available in Firefox but there's a Chrome polyfill you can use.

通过使用 chrome.permissions.request ,您可以添加可以在其上注入内容脚本的新域.一个例子是:

By using chrome.permissions.request you can add new domains on which you can inject content scripts. An example would be:

// 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

For this to work, you'll have to allow new origins to be added on demand by adding this in your manifest.json

{
    "optional_permissions": [
        "http://*/*",
        "https://*/*"
    ]
}


还有一些工具可以为您和最终用户进一步简化此操作,例如


There are also tools to further simplify this for you and for the end user, such as webext-domain-permission-toggle and webext-dynamic-content-scripts, which are used by many GitHub-related extensions to add support for self-hosted GitHub installations.

他们还将在下次浏览器启动时注册您的脚本,并允许用户删除新的权限和脚本.

They will also register your scripts in the next browser launches and allow the user the remove the new permissions and scripts as well.

这篇关于以编程方式在Chrome扩展程序中启用内容脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆