Hi I would like to customize my pop up for leaving a page, is there any simple way to do that?
I am using simple jQuery
$(document).ready(function() {
var myPopUp = $('#pop-up').css('display', 'block');
$(window).bind('beforeunload', function(){
return 'load my pop up here instead of the default browser message';
});
});
my html for the pop up is which is hidden by default
<div id="pop-up">
<h2>Are you sure wanna leave</h2>
<a href="#">Leave</a>
<a href="#" class="close">Stay</a>
</div>
Thanks
Short answer: You can't.
Longer answer: For rather obvious "security" reasons it is very limited what you can do when a user tries to navigate away from a page / close a tab or in any other way leave the site.
The reason is that browsers want to make absolutely sure that you cannot prevent the user from closing a tab or window that he / she wants to close.
Therefore the
onbeforeunload
javascript event - and by extension thebeforeunload
jQuery event - are extremely limited in what they can do. One of the things they definitely cannot do is prevent the page from closing - except using one very standardized and rather boring method the browser (usually) allows.Some browsers allow you to specify a message, while others (including firefox) do not even allow you to change the message (because you might trick the user by asking "Can I adopt your unborn son?")... AFAIK most browsers allow you to specify a string of your choosing in addition to a standard message that cannot be changed. Some browsers (no major desktop browsers) even lack the event completely.
What you want to achieve is basically to force the user to stay on your page, and then show a nice pop-up asking them to confirm... and while this could definitely improve the user experience in a lot of cases, you don't have to think very hard to imagine how it could be abused to simply not allow the user to ever leave.
Think about how annoying sites that break the back-button are, then imagine they could even remove your ability to close a tab!
I stumbled on this rather amusing forum question from a user who has spent an extensive amount of time trying to prevent even what little annoyance can be added - a short excerpt:
And just to add a little bit of somewhat official information:
mozilla.org: WindowEventHandlers.onbeforeunload: