Khanh Tran
Khanh Tran

Reputation: 1826

popstate event handler seems not to work

I'm having a problem with a 'popstate' event handler, this is my code:

window.addEventListener("popstate", function (event){
    if (event.state) {
        alert('abc')
    }
});

// The data object is arbitrary and is passed with the popstate event.
var dataObject = {
    createdAt: '2011-10-10',
    author: 'donnamoss'
};

var url = '/posts/new-url';
history.pushState(dataObject, document.title, url);

I expected this code will pop up an alert box when it's executed but, nothing happens.

Is there anything wrong here?

Thank you.

Upvotes: 17

Views: 28239

Answers (4)

Jeff Hykin
Jeff Hykin

Reputation: 2627

If you are infact calling pushState, then check if the page has iframes anywhere.

Rendering an iframe, then setting the src of the iframe using Javascript, will create a history entry. However, pressing the back button will NOT trigger the top level popstate listener. Because instead it is triggering the popstate inside of the iframe. To a user, they might click the back button and see nothing happen. So technically, yes, popstate listener isn't being triggered. Unfortunately this is intended behavior.

Upvotes: 0

Derek 朕會功夫
Derek 朕會功夫

Reputation: 94319

history.pushState() will not trigger the popstate event by definition.

The popstate event is fired in certain cases when navigating to a session history entry.

This event is intended to be only triggered when navigating to a history entry, either by pressing the back/forward button, or history.go/back.

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388326

No it will not,

As per MDN documentation

Note that just calling history.pushState() or history.replaceState() won't trigger a popstate event. The popstate event is only triggered by doing a browser action such as a click on the back button (or calling history.back() in JavaScript).

Again as per this question the popstate event is not triggered in Chrome when you call pushState().

Upvotes: 7

otakustay
otakustay

Reputation: 12395

pushState do not trigger the popstate event, only clicking back / forward button (or use backspace) or invoking history.back() / history.go(n) would trigger this event.

Also, in webkit browsers, a popstate event would be triggered after page's onload event, but Firefox and IE do not have this behavior.

Upvotes: 30

Related Questions