Chrome扩展程序:如何检测内容脚本已加载到标签中? [英] Chrome Extension: how to detect that content script is already loaded into a tab?

查看:275
本文介绍了Chrome扩展程序:如何检测内容脚本已加载到标签中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在后台脚本中有以下代码:

I have the following code in my background script:

chrome.tabs.onUpdated.addListener(function(tabId, changeinfo, tab) {
    if (changeinfo.status !== 'complete')
        return;

    if (!matchesUrlFilters(tab.url))
        return;

    chrome.tabs.executeScript(tabId, { file: "jquery-1.7.1.min.js" }, function() {
        chrome.tabs.executeScript(tabId, { file: "enhance.js" });
    });
});

但是,在某些情况下,这似乎会注入我的内容脚本两次(可能会发生 enhance.js 确实 window.history.pushState )。

However, this seems to inject my content script twice in some cases (it might happen when enhance.js does window.history.pushState).

我可以找出标签页是否已经有我的内容脚本?我尝试了 chrome.tabs.sendRequest ,但如果内容脚本尚未添加,它从不会调用回调函数。

How can I fInd out whether the tab already has my content script? I tried chrome.tabs.sendRequest but it never called the callback if the content script was not yet added.

推荐答案

编辑:更新每个第一评论这个答案。

Updated per first comment on this answer.

你可能会尝试这样的事情。添加一个onRequest监听器,该监听器将用作回调来加载所需的脚本,但它们只会根据作为请求消息一部分发送的值进行加载。然后使用executeScript直接调用code,发送一个带有全局变量值的消息(如果存在的话)。

You might try something like this. Add a onRequest listener that will be used as a callback to load the scripts you want, but they will only load based on a value sent as part of the request message. Then use executeScript to call "code" directly that sends a message with the value of a global variable (if it exists).

chrome.tabs.onUpdated.addListener(function(tabId, changeinfo, tab) {
    ...

    // execute a content script that immediately sends back a message 
    // that checks for the value of a global variable which is set when
    // the library has been loaded
    chrome.tabs.executeScript(tabId, {
        code: "chrome.extension.sendRequest({ loaded: EnhanceLibIsLoaded || false });"
    });

    ...
});

// listen for requests
chrome.extension.onRequest.addListener(function(req, sender, sendResponse) {
    if (req.loaded === false) {
        chrome.tabs.executeScript(tabId, { file: "jquery-1.7.1.min.js" }, function() {
            chrome.tabs.executeScript(tabId, { file: "enhance.js" }, function() {
                // set the global variable that the scripts have been loaded
                // this could also be set as part of the enhance.js lib
                chrome.tabs.executeScript(tabId, { code: "var EnhanceLibIsLoaded = true;" });
            });
        });
     }
});

这篇关于Chrome扩展程序:如何检测内容脚本已加载到标签中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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