Optionally inject Content Script

前端 未结 3 1818
囚心锁ツ
囚心锁ツ 2020-11-27 17:52

Content Script can be injected programatically or permanently by declaring in Extension manifest file. Programatic injection require host permission, which is generally gran

3条回答
  •  春和景丽
    2020-11-27 18:39

    I'll split this in two parts.

    Programmatic script injection

    There's a new contentScripts.register() API which can programmatically register content scripts and they'll be loaded exactly like content_scripts defined in the manifest:

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

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

    Acquiring new permissions

    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 or options page
    document.querySelector('button').addEventListener('click', () => {
        chrome.permissions.request({
            origins: ['https://your-dynamic-domain.example.com/*']
        }, granted => {
            if (granted) {
                /* Use contentScripts.register */
            }
        });
    });
    

    And you'll have to add optional_permissions in your manifest.json to allow new origins to be requested:

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

    I also wrote some tools to further simplify this for you and for the end user, such as webext-domain-permission-toggle and webext-dynamic-content-scripts. They will automatically register your scripts in the next browser launches and allow the user the remove the new permissions and scripts.

提交回复
热议问题