1
我有一個擴展程序,用於在更新選項卡時注入內容腳本。 主要腳本:使用Chrome擴展程序動態重新載入網頁重新注入內容腳本
chrome.browserAction.onClicked.addListener(function(tab) {
"use strict";
const sendScriptToPage = function(tabId, changeInfo, tab) {
if (changeInfo.status === "complete" && tab && tab.url && tab.url.indexOf("http") === 0) {
console.log ("executeScript ");
chrome.tabs.executeScript(tabId, {
file: "content.js", allFrames: true
});
}
};
chrome.tabs.onUpdated.addListener(sendScriptToPage);
});
內容腳本:
const Content = (function() {
"use strict";
console.log("Content");
const makeRandomColor = function(){
let c = '';
while (c.length < 6) {
c += (Math.random()).toString(16).substr(-6).substr(-1)
}
return '#'+c;
};
document.body.style.backgroundColor = makeRandomColor();
}
)();
,當我重新加載標籤工作正常。但是,當動態重新加載選項卡時,內容腳本會重新加載,儘管它已經加載到選項卡中。這在日誌中顯示,因爲const不能重新聲明。
發生更新時不應該卸載內容腳本?如何知道內容腳本是否已經加載?
,顯示此行爲的網址: http://www.prisjakt.nu/produkt.php?p=391945#rparams=ss=android
在搜索欄中鍵入一些觸發onUpdated事件處理程序,但內容的腳本已經在頁面中。
測試擴展: https://github.com/hawk-lord/chrome-test
謝謝。第一種方法似乎是最方便的。 –