How to make sure a content-script will be loaded into each document using tabs.executeScript?

限于喜欢 提交于 2019-12-11 14:33:17

问题


For my FF extension I was using the content_scripts key in in manifest.json with matches: ['<all_urls>'], but I'm switching to programmatical injections now using browser.tabs.executeScript.

How can I make sure that the script is loaded into each frame on each tab? Do I have to listen for tab's URL changes with browser.tabs.onUpdated or alternatively for the DOMContentLoaded event using browser.webNavigation.onDOMContentLoaded? Or is there a more elegant way of doing this?

The problem with browser.tabs.onUpdated is that it won't fire on URL changes of iFrames with id !== 0. So I experimented with browser.webNavigation.onDOMContentLoaded to overcome this issue (simplified code example):

    browser.webNavigation.onDOMContentLoaded.addListener(infos => {
        const { tabId, frameId } = infos;
        browser.tabs.executeScript(tabId, {
            file: '../path/to/content-script.js',
            frameId
        });
    });

The reason for all this is that I want to let the user enable to opt-out of automatic content script loading and instead do it manually via a pageAction, and also to opt-out of injections into iFrames. So on DOMContentLoaded those 2 settings will be checked, before any injections happen.

In a comment to another question a friendly user suggested I wouldn't even need another API (like webRequests) and that tabs.executeScript would suffice - I wonder how? Is there another way of conditionally injecting content scripts?

来源:https://stackoverflow.com/questions/56935506/how-to-make-sure-a-content-script-will-be-loaded-into-each-document-using-tabs-e

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!