我的后台脚本中有以下代码:
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
)。
如何确定选项卡是否已包含我的内容脚本?我试过了 chrome.tabs.sendRequest
但如果尚未添加内容脚本,它从不调用回调。
编辑:对此答案的第一条评论进行了更新。
你可能会尝试这样的事情。添加一个onRequest侦听器,该侦听器将用作回调以加载所需的脚本,但它们仅基于作为请求消息的一部分发送的值进行加载。然后使用executeScript直接调用“代码”,发送带有全局变量值(如果存在)的消息。
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;" });
});
});
}
});