Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

popstate event handler seems not to work

Tags:

javascript

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.

like image 386
Khanh Tran Avatar asked Jan 01 '13 17:01

Khanh Tran


People also ask

How do you trigger a Popstate event?

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.

What is Popstate event listener?

PopStateEvent is an interface for the popstate event. A popstate event is dispatched to the window every time the active history entry changes between two history entries for the same document. If the history entry being activated was created by a call to history. pushState() or was affected by a call to history.


2 Answers

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.

like image 71
otakustay Avatar answered Oct 18 '22 14:10

otakustay


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().

like image 6
Arun P Johny Avatar answered Oct 18 '22 13:10

Arun P Johny