Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

addEventListener("popstate") not firing for .document

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.

like image 922
NickC Avatar asked Sep 15 '16 16:09

NickC


People also ask

How do I trigger a popstate event?

Note that just calling history.pushState () or history.replaceState () won't trigger a popstate event. The popstate event will be triggered by doing a browser action such as a click on the back or forward button (or calling history.back () or history.forward () in JavaScript).

Can I create a popstate event handler on an Ajax page?

Using Ajax and trying to create a popstate event handler on the actual Ajax page using the .document object: Unfortunately this does not ever seem to trigger. My intention being that after the page is reloaded the popstate event trigger will automatically disappear. Show activity on this post.

Does the popstate event trigger automatically disappear after page reload?

Unfortunately this does not ever seem to trigger. My intention being that after the page is reloaded the popstate event trigger will automatically disappear. Show activity on this post.

What is the use of addEventListener?

The addEventListener () method attaches an event handler to a document. Required. The event name. Do not use the "on" prefix. Use "click" instead of "onclick". HTML DOM Event Object Reference.


1 Answers

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 '';
});
like image 92
manikant gautam Avatar answered Oct 26 '22 23:10

manikant gautam