简体   繁体   中英

How to restore Browser Back button after disable it using button?

I am disabling browser back button with below code. I can't figure out how to resotre Browser Back button after clicking a button.

 history.pushState(null, null, location.href); window.onpopstate = function () { history.go(1); }; (function($) { $('button').on('click', function() { history.pushState(null, null, location.href); window.onpopstate = function () { history.go(-1); }; }); })(jQuery);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button>Click</button>

Generally, when you want to override something then restore it later, you take a copy:

var oldpopstate = window.onpopstate;
window.onpopstate = function() { history.go(1); };

$("#restore").click(() => window.onpopstate = oldpopstate );

Alternatively, check inside the function:

var enabled = true;
window.onpopstate = function() { if (enabled) history.go(1); };

$("#restore").click(() => enabled = false );

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