您可以在内容脚本中添加一个window.onpopstate事件并监听它,当事件触发时,您可以再次重新运行内容脚本。
参考
a) extension.sendMessage()
b) extension.onMessage().addListener
c) tabs.executeScript()
d) history.pushState()
e) window.onpopstate
示例演示:
清单.json
确保内容脚本注入 URL 和所有 API 的选项卡在清单文件中具有足够的权限
{
"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");
背景.js
跟踪来自内容脚本的请求并将脚本执行到当前页面
//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");
输出
如果您需要更多信息,请与我们联系。