Dmi*_*kin 6 javascript google-chrome browser-history google-chrome-extension vk
我正在为网站创建一个小的谷歌浏览器扩展程序,我想在特定页面上更改一些HTML.
问题是网站通过ajax加载他的内容,并且大量使用history.pushState API.所以,我添加了这个东西来表明:
"content_scripts": [
{
"matches": ["http://vk.com/friends"],
"js": ["js/lib/jquery.min.js", "js/friends.js"],
},
]
Run Code Online (Sandbox Code Playgroud)
当我第一次打开页面或重新加载它时,一切正常.但是当我在网站页面之间导航时,chrome不会在"/ friends"页面上插入我的脚本.我认为这发生了,因为URL实际上没有改变.他们使用history.pushState()等,chrome无法再次插入/重新运行我的脚本.
这有什么解决方案吗?
phi*_*oye 12
我能够让这个工作.来自适用于webNavigation的Chrome扩展程序文档:
您需要webNavigation
在manifest.json中设置权限:
"permissions": [
"webNavigation"
],
Run Code Online (Sandbox Code Playgroud)
然后在background.js中:
chrome.webNavigation.onHistoryStateUpdated.addListener(function(details) {
console.log('Page uses History API and we heard a pushSate/replaceState.');
// do your thing
});
Run Code Online (Sandbox Code Playgroud)
您可以在内容脚本中添加window.onpopstate事件并监听它,当事件触发时您可以再次重新运行内容脚本。
参考
b) extension.onMessage().addListener
示例演示:
清单文件
确保内容脚本注入的 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/"]
}
Run Code Online (Sandbox Code Playgroud)
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");
Run Code Online (Sandbox Code Playgroud)
背景.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");
});
}
});
Run Code Online (Sandbox Code Playgroud)
重新运行注入.js
一些琐碎的代码
console.log("Injected again");
Run Code Online (Sandbox Code Playgroud)
输出
如果您需要更多信息,请与我们联系。
归档时间: |
|
查看次数: |
6542 次 |
最近记录: |