我的后台脚本中有以下代码:
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
does window.history.pushState
).
如何查明该选项卡是否已有我的内容脚本?我试过chrome.tabs.sendRequest
但如果尚未添加内容脚本,它永远不会调用回调。
编辑:根据对此答案的第一条评论进行更新。
你可以尝试这样的事情。添加一个 onRequest 侦听器,该侦听器将用作回调来加载所需的脚本,但它们只会根据作为请求消息的一部分发送的值进行加载。然后使用executeScript直接调用“code”,发送带有全局变量值(如果存在)的消息。
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;" });
});
});
}
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)