Sergio Marani
Sergio Marani

Reputation: 87

Why window.onpopstate is called twice using history.go?

I've find this code that provides to disable browser back button using javascript. It works but when i press the back button it calls the console.log twice. Why?

history.pushState(null, null, location.href);
window.onpopstate = function () {
    history.go(1);
    console.log("back");
};

Upvotes: 2

Views: 2069

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337590

It's called twice because onpopstate is triggered once when the Back button is clicked in the browser. Then you call history.go(1) again which moves the history forward and hence calls popstate one more time.

Technically that also calls history.go(1) again, which would create an infinite loop, but as you're at the top of the history stack, nothing happens.

Note that if you're expecting this to be a reliable way of disabling the back button, it's not. I can easily right click the back button and go to any item in the history.

There is no reliable way to disable the back button - and this is by design.

Upvotes: 3

Related Questions