Javascript 通过history.pushState更改页面时,如何在google chrome扩展中插入内容脚本?

Javascript 通过history.pushState更改页面时,如何在google chrome扩展中插入内容脚本?,javascript,google-chrome,google-chrome-extension,browser-history,vk,Javascript,Google Chrome,Google Chrome Extension,Browser History,Vk,我正在为网站创建一个小的google chrome扩展,我想在特定页面上更改一些html 问题是网站通过ajax加载他的内容,并且大量使用history.pushState API。 所以,我添加了这个东西来显示: "content_scripts": [ { "matches": ["http://vk.com/friends"], "js": ["js/lib/jquery.min.js", "js/friends.js"], }, ] 当我第

我正在为网站创建一个小的google chrome扩展,我想在特定页面上更改一些html

问题是网站通过ajax加载他的内容,并且大量使用history.pushState API。 所以,我添加了这个东西来显示:

"content_scripts": [
   {
     "matches": ["http://vk.com/friends"],
     "js": ["js/lib/jquery.min.js", "js/friends.js"],      
   },
 ]
当我第一次打开或重新加载页面时,一切正常。 但当我在网站页面之间导航时,chrome不会在“/朋友”页面上插入我的脚本。我认为这是因为URL实际上没有改变。他们使用history.pushState(),因此chrome无法再次插入/重新运行我的脚本

有什么解决方案吗?

您可以在内容脚本中添加事件并侦听它,当事件激发时,您可以再次运行内容脚本

参考资料

(a)

(b)

(c)

(d)

(e)

示例演示:

manifest.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\u 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

跟踪来自内容脚本的请求,并将脚本执行到当前页面

//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");
输出


如果您需要更多信息,请告诉我。

我可以让它正常工作。从:

您需要在manifest.json中为
webNavigation
设置权限:

  "permissions": [
     "webNavigation"
  ],
  chrome.webNavigation.onHistoryStateUpdated.addListener(function(details) {
        console.log('Page uses History API and we heard a pushSate/replaceState.');
        // do your thing
  });
然后在background.js中:

  "permissions": [
     "webNavigation"
  ],
  chrome.webNavigation.onHistoryStateUpdated.addListener(function(details) {
        console.log('Page uses History API and we heard a pushSate/replaceState.');
        // do your thing
  });
顺便说一句,pushState不会触发“popstate”事件,因此此代码不起作用。