I don't want this to seem too grey hat, but does anyone have any code or a link to any javascript code that will bring up a confirmation box when someone goes to leave my site? I'd like to offer the user the ability to go checkout another one of my similar sites if they don't see what they like, before completely leaving my site. I tried Googling for some code like this, but I'm really not sure what it would be called or labeled as, so I came up empty handed.
I have never seen such a script before, and it doesn't even sound feasible. How can Javascript detect when a user is going to leave the page? I could press ctrl-w to close it, backspace to go back to Google (assuming I came from there), or I could click the buttons. That said, this might work although it isn't valid. I would link to give credit, but I don't have enough posts...
Yes, you can use the following example, replacing function doPageExit() with your own popup code: <html> <head> <script type="text/javascript"> function finit() { if (typeof window.attachEvent != 'undefined') { // this works for IE window.attachEvent('onbeforeunload', doPageExit); } else if (typeof window.addEventListener != 'undefined') { // this works for firefox window.addEventListener('beforeunload', doPageExit, false); } } function doPageExit() { alert( "Do you really want to exit ?" ); } </script> </head> <body onLoad="finit();"> <a href="http://www.google.com">Go to Google</a> </body> </html> Code (markup):
There you go. Not foolproof of course, as the user can and might possibly have disabled Javascript. Also, don't you think this might get annoying after a while? I wouldn't put this on a serious site if I were you, but that's your initiative. I am surprised there was even a way to do this.