简体   繁体   中英

removing eventlistener for beforeunload

I'm trying to implement a popup (bootstrap modal style) that would be triggered as web visitor leaves my site.

I tried different alternatives of:

$(window).bind('beforeunload', function(){
$("#sModal").modal('show');
return 'Take our survey before you leave.';
});

However, it didn't work in FF while worked fine in IE. I had another problem also, that the "Do you want to leave or stay" alert was being displayed on any link click on my website itself, across all browser types, as the whole page was being loaded.

I got around this by looping through all my anchor tags and adding a click listener to remove the beforeunload listener using:

window.onload = function () {
    var allLinks = document.getElementsByTagName('a');
    for (var i = 0; i < allLinks.length; i++) {
        allLinks[i].addEventListener("click", removeBeforeUnload, false);
    }
};

The removeBeforeUnload function just used the

$(window).unbind('beforeunload');

Getting back to actually make the popoup/modal appear on all browsers, i used the code from this stackoverflow answer after my document completes loading:

window.onbeforeunload and window.onunload is not working in Firefox , Safari , Opera?

This solution works great across all browsers, however now I cannot unbind this event on any of my local clicked links! I tried everything

window.removeEventlistener('beforeunload',null,false);
window.removeEventlistener('onbeforeunload',null,false);
window.removeBeforeUnload();
window.onbeforeunload = null;

I hope you can point me in the right direction and explain why I cannot unbind this event, that I used from stackoverflow answer.Thanks!

Probably jQuery is adding a 2nd beforeunload event listener, which you can't remove via the DOM API the same way as the one added to the Window by default.

What should work for you is:

var allLinks = $('a');
  for (var i = 0; i < allLinks.length; i++) {
    $(allLinks[i]).on('click', () => {
      $(window).off('beforeunload');
      // now add any custom code you want for handling this event
      $("#sModal").modal('show');
    )};
  }

One thought is use a global variable flag and don't do anything in the unload event handler when flag isn't truthy. Set this flag to null or false in link click handlers

Then you don't really need to remove the listener

var doUnload = true;

$('a').click(function(){
   doUnload = false;
});

function unloadhandler(){
    if(doUnload){
       // show modal , return message etc
    }else{
       // do nothing , don't return anything
    }       
}

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