When the back button triggers popState how can I prevent a page refresh?

前端 未结 2 1189
独厮守ぢ
独厮守ぢ 2020-12-24 06:50

I am trying to modify the content in my page without a reload. Currently my code reads:

window.onpopstate = function(event){
    // Ajax Request the Page and         


        
2条回答
  •  醉梦人生
    2020-12-24 07:21

    This may help

    The unload event is sent to the window element when the user navigates away from the page. This could mean one of many things. The user could have clicked on a link to leave the page, or typed in a new URL in the address bar. The forward and back buttons will trigger the event. Closing the browser window will cause the event to be triggered. Even a page reload will first create an unload event.

    Reference

    http://api.jquery.com/unload/

    untested

        $(window).unload(function(e){    
            e.preventDefault();
            $(window).trigger('popstate ');      
    
        });    
    
        $(window).bind('popstate ',function(){
    
       //your ajax call here 
        });
    

    and finally here is a DEMO click on browser's back button to see it working

    update

    you are right the unload be canceled but you can do some thing like

    $(window).unload(function(e){
        e.preventDefault();
        $(window).trigger('beforeunload');   
    
    });
    
    
    $(window).bind('beforeunload',function(){
    
    alert('call your ajax here');
        return '';
    });
    

    yet another DEMO

提交回复
热议问题