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

Viewed 73

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>

1 Answers

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 );
Related