Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 276
Dmitry Chirkin Avatar asked Dec 10 '12 17:12

Dmitry Chirkin


1 Answers

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
  });
like image 200
philoye Avatar answered Sep 26 '22 07:09

philoye