简体   繁体   中英

How to get browser go back button event and prevented from default behavior

with respect to browser default go back button behavior . my app have a special case to ignore it on certain conditions for example . i have modal if the modal is opened instead of going back just close the modal. i have no idea if it's possible or not any help

function keyEventClose(event){
        var status = $('#myModal').is(':visible');
        if(status){
        //prevent from going back just close the modal
        $('#myModal').modal('hide');
        }else{
        //go back as default 
          window.history.back();
        }
    }

after looking for an hour finally find the solution to this problem . as i did not find a current answer here. so this answer maybe helpful for some one.

$('#openfeed').on('shown.bs.modal', function() {
    var stateObj = { foo: "modal-opened" };
    history.pushState(stateObj, "modal-opened", "modal-opened");
})

window.addEventListener('popstate', function(event) {
  $('#openfeed').modal('hide');
});

as you can see when ever the modal is opened we create fake URL in history by pushState() (browser do not check for URLs created by this function so no reload on the page) when ever browser go back is pressed an popstate `event is generated after attaching this event to document the problem solved .

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