views:

401

answers:

2

My boss wants our site to show an alert if a customer tries to exit the site with items in the cart.

How can I show an alert when the user tries to exit our site? Also I don't want to show the alert if they are just navigating to another page on our site, but only if they are navigating completely away from our site.

P.S. I am not using any frameworks.

+2  A: 

There's no simple way to detect leaving a domain. You can detect leaving a page easily with the onBeforeUnload event, but leaving the entire domain isn't so simple. As suggested here, you could probably do this by implementing a single master page that loads all pages in an iframe...

Kaleb Brasee
A: 

Whilst you can use the onbeforeunload event to determine that the page is trying to leave the site, you can not get the new URL that the page is going to even if it is on your own site as this is a security violation.

The only workaround that I can think of is as suggested in another post by either using a Iframe or full frame, but that gives the difficulty of URL being static and therefore prevents bookmarking.

E.g.:

frame.htm

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
  "http://www.w3.org/TR/html4/strict.dtd"&gt;
<html>
  <head>
    <script language='JavaScript' type='text/javascript'>
      window.onbeforeunload = function (evt) {
        return "This is a demonstration that you are leaving me";
      }
    </script>

    <frameset border='0' rows="*">
      <frame src='test_page.htm' border=0 scrolling=no frameborder=0 noresize name=top>
    </frameset>
  </body>
</html>

E.g. Test Page

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  <head>
  </head>
  <body>
    Hello World
    <p>
    <a href='javascript:top.location.href="http://www.google.com"'&gt; Outside link Google</a>
    </p>
    <p>
    <a href='http://www.google.com'&gt; Inside frame link to Google</a>
    </p>
  </body>
</html>

This allows you to navigate to a link either inside the frame or outside the frame (just as an example both to the same destination). But only if you go outside or close the browser will you be asked if you want to do this?

Dave