您可以在内容脚本中添加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”事件,所以这段代码不起作用。 –