检测Chrome扩展内容脚本是否已注入/内容脚本是否包含保护

detect if Chrome extension content script has been injected / content script include guard

本文关键字:是否 脚本 包含 保护 注入 检测 Chrome 扩展      更新时间:2023-09-26

每当更新选项卡时,我都想执行一个内容脚本函数。问题是,有时选项卡更新是ajax(不需要重新加载页面),同时仍在更改页面的url。因此,注入的旧内容脚本仍然存在于页面上。结果是在同一页面上注入并运行多个内容脚本实例。

因此,我正在寻找一种注入内容脚本的机制,前提是以前没有注入过相同的内容脚本。有什么想法吗?

您可以尝试向内容脚本发送消息(消息传递)。如果内容脚本成功返回响应,则表示内容脚本已经存在,否则返回空响应,您可以检查空响应并注入内容脚本。

背景:

chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
    chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, function(response) {
        if (response) {
            console.log("Already there");
        }
        else {
            console.log("Not there, inject contentscript");
        }
    });
});

内容脚本:

chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) {
        if (request.greeting == "hello")
            sendResponse({message: "hi"});
 });

实现包含保护非常容易:

(function() {
    // Comparing to a literal value to prevent matching a DOM element with id="hasRun"
    // https://stackoverflow.com/q/3434278/do-dom-tree-elements-with-ids-become-global
    if (window.hasRun === true) return;
    window.hasRun = true;
    // Rest of code
})();

如果要以编程方式注入内容脚本,请考虑使用webNavigation事件之一(例如onCommitted)而不是chrome.tabs.onUpdated。与tabs事件不同,webNavigation事件也被触发用于帧内的导航,并提供了一种提前声明URL过滤器的方法。