2

I have searched everywhere and I cannot find the exact solution that I am looking for. I need a javascript code that when the user tries to exit the page, an alert box pops up with the "stay on page" or "leave page" options. If the user stays, it redirects them to another page and if they choose leave it leaves. Something similar to exit splash. I know this is poor practice but it is what the clients wants. Any help will be greatly appreciated. Thanks in advance for your help.

Joax23
  • 25
  • 1
  • 6
  • 1
    can only ask them if they want to leave or not using `onbeforeunload`... if everyone could redirect you the web would be a nightmare – charlietfl Nov 14 '13 at 21:55
  • Dupe: http://stackoverflow.com/questions/2663728/how-to-display-onbeforeunload-dialog-when-appropriate – Diodeus - James MacFarlane Nov 14 '13 at 21:56
  • That is just for the alert box, I need a redirect if they choose stay on page. – Joax23 Nov 14 '13 at 22:04
  • @user2994045 it can't be done. Like I said, if everyone could it would be a nightmare. Client will have to accept that. Dig into the browser docs like : https://developer.mozilla.org/en-US/docs/Web/API/Window.onbeforeunload. Can return a string only, no callback – charlietfl Nov 14 '13 at 22:08

2 Answers2

3

This is hacky but will do the job

var triedToLeave = false;
function onBeforeUnload(){
    triedToLeave = true;
    return "you can put your own message here";
}
setInterval( function (){
     if( triedToLeave ){
         window.removeEventListener( "beforeunload", onBeforeUnload, false );
         document.location.href = "http://stackoverflow.com/";
     }
}, 2000 );
window.addEventListener( "beforeunload", onBeforeUnload, false);

EDIT fixed function

gotofritz
  • 3,341
  • 1
  • 31
  • 47
1

This should accomplish the final result you want, though it technically directs the user to the splash page before they make their decision.

var notScriptLeaving = true;
window.onbeforeunload = function() {
    if (notScriptLeaving) {
        notScriptLeaving = false;
        window.location = 'http://www.example.com/'; //Splash page url goes here
        return "Are you sure you want to navigate away?";
    }
}
AlliterativeAlice
  • 11,841
  • 9
  • 52
  • 69