简体   繁体   中英

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");
};

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM