Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect when history.pushState and history.replaceState are used? [duplicate]

Is there some event I can subscribe to when the history state is modified? How?

like image 490
BrunoLM Avatar asked Feb 26 '11 20:02

BrunoLM


People also ask

How do I check my pushState history?

To detect the changes in the browser's history whenever history. pushState() method is called, we would have to monkey-patch (change the behavior of existing function similar to overriding) an object called window. history.

What is the difference between pushState and replaceState?

The big difference is, that while pushState will create a new entry in the browser's history, replaceState will only replace the current state. As a side effect of this, using the replaceState method will change the URL in the address bar, without creating a new history entry.

Does history pushState reload page?

HTML5 History API allows browsers to change the URL in browser address bar without reloading or refreshing the page using pushState function. The pushState method works similar to window.

What triggers Onpopstate?

The popstate event will be triggered by doing a browser action such as a click on the back or forward button (or calling history. back() or history. forward() in JavaScript). Browsers tend to handle the popstate event differently on page load.


1 Answers

I used to use this to also be notified of when pushState and replaceState are called:

// Add this: var _wr = function(type) {     var orig = history[type];     return function() {         var rv = orig.apply(this, arguments);         var e = new Event(type);         e.arguments = arguments;         window.dispatchEvent(e);         return rv;     }; }; history.pushState = _wr('pushState'), history.replaceState = _wr('replaceState');  // Use it like this: window.addEventListener('replaceState', function(e) {     console.warn('THEY DID IT AGAIN!'); }); 

It's usually overkill though. And it might not work in all browsers. (I only care about my version of my browser.)

NB. It also doesn't work in Google Chrome extension content scripts, because it's not allowed to alter the site's JS environment. You can work around that by inserting a <script> with said code, but that's even more overkill.

like image 53
Rudie Avatar answered Sep 23 '22 23:09

Rudie