addEventListener("popstate") not firing for .document

NickC picture NickC · Sep 15, 2016 · Viewed 11.1k times · Source

Using Ajax and trying to create a popstate event handler on the actual Ajax page using the .document object:

document.addEventListener("popstate", myPopState);

Unfortunately this does not ever seem to trigger.

My intention being that after the page is reloaded the popstate event trigger will automatically disappear.

Answer

manikant gautam picture manikant gautam · Sep 15, 2016

inside ajax success response , you could use

         var msg="Any thing which u want";
         var customUrl ="www.stackoverflow.com";

 window.history.pushState({"html":msg,"pageTitle":"My Title"},"", customUrl);
       window.onpopstate = function(event) {
             alert('back is clicked');
           // what ever u want
       }

UPDATE

$(window).unload(function(e){
    e.preventDefault();
    $(window).trigger('beforeunload');   

});


$(window).bind('beforeunload',function(){

alert('call your ajax here');
    return '';
});