1

I have a website that changes the URL without reloading with the following command on Chrome:

window.history.pushState(“object or string”, “Title”, “/new-url”);

Is there a way to detect such an event from Javascript? I tried this, but it doesn't work:

$(window).bind('hashchange', function() {
    alert("CHANGED!!");
});  
  • Why don't you trigger your own custom event? – A. Wolff Jul 11 '16 at 16:08
  • The website is not really mine, is SLACK. And I am just writing a Chrome Extension... –  Jul 11 '16 at 16:09
  • I mean if it's your own code that calls `pushState`, then just after that, trigger any custom event (or popstate one e.g), see [trigger()](http://api.jquery.com/trigger/) – A. Wolff Jul 11 '16 at 16:14
  • Unfortunately that is not my own code. My Chrome extension is the one that needs to detect the URL change. Any possibility to do this even if it requires timers and loops? –  Jul 11 '16 at 16:16
  • 1
    You can just re-define the `history.pushState` function, adding your custom event logic, and then `apply` the original function. See this answer: http://stackoverflow.com/a/4585031/1814840. You just need to inject it into the page on load using a content script. – Gideon Pyzer Jul 11 '16 at 16:19

1 Answers1

2

Only for Chrome Extensions

Given:

var stateObj = { foo: "bar" };
history.pushState(stateObj, "page 2", "yourwebsite.com/page2");

you can detect it with this:

chrome.webNavigation.onHistoryStateUpdated.addListener(function(e) {
        console.log(e);
      }, {url: [{hostEquals: 'yourwebsite.com'});
Thoran
  • 8,884
  • 7
  • 41
  • 50