您可以在內容腳本中添加window.onpopstate事件並偵聽它,當事件觸發時,您可以再次重新運行內容腳本。
參考
一個)extension.sendMessage()
b)中extension.onMessage().addListener
c)中tabs.executeScript()
d)history.pushState()
E)window.onpopstate
示例演示:
的manifest.json
確保內容腳本注入URL和所有API的標籤有足夠的權限在manifest文件
個
{
"name": "History Push state Demo",
"version": "0.0.1",
"manifest_version": 2,
"description": "This demonstrates how push state works for chrome extension",
"background":{
"scripts":["background.js"]
},
"content_scripts": [{
"matches": ["http://www.google.co.in/"],
"js": ["content_scripts.js"]
}],
"permissions": ["tabs","http://www.google.co.in/"]
}
content_scripts.js
跟蹤onpopstate事件,併發送至後臺頁面的請求腳本的重播
window.onpopstate = function (event) {
//Track for event changes here and
//send an intimation to background page to inject code again
chrome.extension.sendMessage("Rerun script");
};
//Change History state to Images Page
history.pushState({
page: 1
}, "title 1", "imghp?hl=en&tab=wi");
background.js
軌道針對來自內容腳本的請求T和執行腳本到當前頁面
//Look for Intimation from Content Script for rerun of Injection
chrome.extension.onMessage.addListener(function (message, sender, callback) {
// Look for Exact message
if (message == "Rerun script") {
//Inject script again to the current active tab
chrome.tabs.executeScript({
file: "rerunInjection.js"
}, function() {
console.log("Injection is Completed");
});
}
});
rerunInjection。JS
一些瑣碎的代碼
console.log("Injected again");
輸出
讓我知道如果你需要更多的信息。
順便說一句,pushState的不火「popstate」事件,所以這段代碼不起作用。 –