Tru*_*nse 6 google-chrome-extension
我有一个chrome扩展,它为每个打开的标签注入一个iframe.我在我的background.js中有一个chrome.runtime.onInstalled监听器,它按如下方式手动注入所需的脚本(这里有API的详细信息:http://developer.chrome.com/extensions/runtime.html#event-onInstalled):
background.js
var injectIframeInAllTabs = function(){
console.log("reinject content scripts into all tabs");
var manifest = chrome.app.getDetails();
chrome.windows.getAll({},function(windows){
for( var win in windows ){
chrome.tabs.getAllInWindow(win.id, function reloadTabs(tabs) {
for (var i in tabs) {
var scripts = manifest.content_scripts[0].js;
console.log("content scripts ", scripts);
var k = 0, s = scripts.length;
for( ; k < s; k++ ) {
chrome.tabs.executeScript(tabs[i].id, {
file: scripts[k]
});
}
}
});
}
});
};
Run Code Online (Sandbox Code Playgroud)
这在我第一次安装扩展时工作正常.我希望在更新扩展程序时也这样做.如果我也在更新时运行相同的脚本,我没有看到注入新的iframe.不仅如此,如果我尝试在更新后向我的内容脚本发送消息,则所有消息都不会进入内容脚本.我见过其他人也在SO上遇到同样的问题(Chrome:在runtime.onInstalled上的消息内容脚本).在chrome扩展更新后删除旧内容脚本和注入新内容脚本的正确方法是什么?
当扩展程序更新时,Chrome 会自动切断所有“旧”内容脚本与后台页面的对话,如果旧内容脚本确实尝试与运行时通信,它们也会抛出异常。这对我来说是缺失的部分。我所做的只是在chrome.runtime.onInstalledin 中bg.js调用与问题中发布的方法相同的方法。这会注入另一个与正确运行时对话的 iframe。在某个时间点,旧的内容脚本会尝试与失败的运行时对话。我捕获了该异常并清除了旧的内容脚本。还要注意的是,每个 iframe 都被注入到它自己的“孤立世界”(孤立世界在这里解释:http : //www.youtube.com/watch?v=laLudeUmXHM)因此新注入的 iframe 无法清除旧的挥之不去的 iframe。
希望这对将来的人有所帮助!