Jquery when back button is pressed

给你一囗甜甜゛ 提交于 2019-11-30 17:27:53

You can sort of do it using the popstate event:

window.onpopstate = function() {
  alert("pop!");
}

or in jQuery:

$(window).on('popstate', function(event) {
 alert("pop");
});

However this will also trigger when navigating forward, not only backward.

Disable back url

$(function() {
    if (window.history && window.history.pushState) {
        window.history.pushState('', null, './');
        $(window).on('popstate', function() {
            // alert('Back button was pressed.');
            document.location.href = '#';

        });
    }
});
iamitpkumar

You can simply fire the “popState” event in JQuery e.g:

$(window).on('popstate', function(event) {
    alert("pop");
});

This is enough for what you asked … but here are few add on window event to go with…

$(window).on('pushstate', function(event) {
    alert("push");
}); // This one pushes u to forward page through history...

window.history.replaceState(); //work exactly like pushstate bt this one replace the history instead of creating new one...
window.history.backward(); // To move backward through history, just fire this event...
window.history.forward();// To move forward through history ...
window.history.go(-1); // Go back to one page(or whatever value u passed) through history
window.history.go(1); // Go forward to one page through history..
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!