addEventListener("popstate") not firing for .document
Asked Answered
B

1

6

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.

Blackwood answered 15/9, 2016 at 16:18 Comment(1)
window.addEventListener("popstate", myPopState);Lepidopteran
U
1

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 '';
});
Unschooled answered 15/9, 2016 at 16:21 Comment(4)
but doesn't the onpopstate event listener then remain permanently so it continues to get called everytime 'back' is clicked?Blackwood
@Blackwood you can bind call on document.Unschooled
How would I do that? window.addEventListener("popstate", myPopState).bind(document) ?Blackwood
Any way to do it without JQuery?Blackwood

© 2022 - 2024 — McMap. All rights reserved.