Javascript Alert When Leaving The Site?

Discussion in 'JavaScript' started by natekapi, Feb 26, 2007.

  1. #1
    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.
     
    natekapi, Feb 26, 2007 IP
  2. chaos0784

    chaos0784 Peon

    Messages:
    33
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    0
    #2
    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...
     
    chaos0784, Feb 26, 2007 IP
  3. ajsa52

    ajsa52 Well-Known Member

    Messages:
    3,426
    Likes Received:
    125
    Best Answers:
    0
    Trophy Points:
    160
    #3
    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):
     
    ajsa52, Feb 26, 2007 IP
  4. chaos0784

    chaos0784 Peon

    Messages:
    33
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    0
    #4
    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.
     
    chaos0784, Feb 26, 2007 IP
  5. Greg-J

    Greg-J I humbly return to you.

    Messages:
    1,844
    Likes Received:
    153
    Best Answers:
    0
    Trophy Points:
    135
    #5
    Exit popups are actually quite useful in the right situations.
     
    Greg-J, Feb 27, 2007 IP