Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

history.pushState does not trigger 'popstate' event

Tags:

Why

$(function () {   $(window).bind('popstate', function () {alert('pop');});    window.history.pushState(null, '', '/foo'); }); 

does not alert pop ?

NB: Testing on latest chrome

--

According to MDN:

A popstate event is dispatched to the window every time the active history entry changes. If the history entry being activated was created by a call to pushState or affected by a call to replaceState, the popstate event's state property contains a copy of the history entry's state object.

So why my pushState does not trigger the popstate event?

like image 589
abernier Avatar asked Jun 07 '12 22:06

abernier


People also ask

Does pushState trigger Popstate?

html - history. pushState does not trigger 'popstate' event - Stack Overflow. Stack Overflow for Teams – Start collaborating and sharing organizational knowledge.

Does history back trigger Popstate?

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.

Which event is fired when the history of the browser window changes?

HTML DOM PopStateEvent Events that occur when the window's history changes.

What is the use of history pushState?

In an HTML document, the history. pushState() method adds an entry to the browser's session history stack.


2 Answers

You can manually trigger popstate event on window every time you call history.pushState().

history.pushState(state, '', url);  var popStateEvent = new PopStateEvent('popstate', { state: state }); dispatchEvent(popStateEvent); 
like image 98
sgtpep Avatar answered Sep 18 '22 14:09

sgtpep


The paragraph you reference is a little ambiguous. Reading the example on the same page, it is clear that popstate is only triggered when the user clicks the back button, not when the script calls pushState().

like image 33
Sean Hogan Avatar answered Sep 18 '22 14:09

Sean Hogan