How to insert content script in google chrome extension when page was changed via history.pushState?

Dmitry Chirkin picture Dmitry Chirkin · Dec 10, 2012 · Viewed 7.2k times · Source

I'm creating a small google chrome extension for website, and I want to change some html on particular pages.

The problem is that website load his content via ajax, and heavy use history.pushState API. So, I added this thing to manifest:

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

Everything works fine when I'm opening page first time or reloading it. But when I'm navigating between website pages, chrome don't insert my scripts on "/friends" page. I think this happening because the URL actually don't changing. They use history.pushState() and so, chrome can't insert/rerun my script again.

Is there any solution for this?

Answer

philoye picture philoye · Jul 11, 2013

I was able to get this working. From the Chrome Extension docs for webNavigation:

You need to set permissions for webNavigation in manifest.json:

  "permissions": [
     "webNavigation"
  ],

Then in background.js:

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