5

我正在为网站创建一个小的Google Chrome扩展,并且我想在特定页面上更改一些html。如何通过history.pushState更改页面时如何在Google Chrome扩展插入内容脚本?

问题是,网站通过ajax加载他的内容,并大量使用history.pushState API。 所以,我说这个东西来体现:当我打开网页第一次或重装它

"content_scripts": [ 
    { 
    "matches": ["http://vk.com/friends"], 
    "js": ["js/lib/jquery.min.js", "js/friends.js"],  
    }, 
] 

,一切工作正常。 但是,当我在网页之间浏览时,chrome不会将我的脚本插入“/ friends”页面。我认为这是因为URL实际上没有改变。他们使用history.pushState()等,铬不能再次插入/重新运行我的脚本。

有没有解决方案?

回答

3

您可以在内容脚本中添加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"); 

输出

enter image description here

让我知道如果你需要更多的信息。

+3

顺便说一句,pushState的不火“popstate”事件,所以这段代码不起作用。 –

7

我能够得到这个工作。从Chrome Extension docs for webNavigation

您需要设置webNavigation权限manifest.json的

"permissions": [ 
    "webNavigation" 
    ], 

然后在background.js

chrome.webNavigation.onHistoryStateUpdated.addListener(function(details) { 
     console.log('Page uses History API and we heard a pushSate/replaceState.'); 
     // do your thing 
    }); 
相关问题