views:

2346

answers:

3

Hello Everyone,

I'm trying to get this Javascript to work properly. My intention is, when a user is trying to close the site page to get an alert saying "stay on current page or close" If they hit 'ok' I want it to close, if they hit 'cancel' i want it to redirect to another page. The problem is, when they try to go to another page on the same site, it gives them that popup. I want it to show only when closing, not when leaving the page to another page. I'm not sure if that's possible, I do appreciate your help and comments.

    window.onbeforeunload = fget;
function yPop(url) {
  var found = 1;
  window.onbeforeunload = '';
  window.location = url;
  return false;
}
function fget() {
  alert("Thank you for visiting our website, you are welcome any time! \n\n");
  window.location = "http://NewLink.com";
  return "\n________________________\n\n PRESS 'CANCEL' To Stay On The Current Page \n\n________________________\n";
}
A: 

you should use the window onbeforeunload Event.

http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx

https://developer.mozilla.org/en/DOM/window.onbeforeunload

for jquery users :

$(window).unload( function () { alert("Bye now!"); } );
Moran
+16  A: 

The problem is, when they try to go to another page on the same site, it gives them that popup. I want it to show only when closing

  1. Don't do this.

  2. You can't detect closing only, but you can tell the difference between leaving by clicking on an internal link and other kinds of leaving, including external links, back button, closing and choosing/typing a new URL. In a script after the page has loaded, set the onbeforeunload event, then scan over all the document.links and test their .host against the current location.host. If they match, it's an internal link. In this case add an onclick event to them that removes the onbeforeunload event before returning true, allowing the link to operate normally without a warning.

  3. Seriously, don't do this. It is incredibly irritating, arrogant and useless. Webmasters who employ leaving-pester scripts are condemned to the the fourth circle of internet hell, where they must spend the rest of eternity making stylesheets work on Netscape 4 using only ed, a worn toothbrush and a < layer>-tag.

bobince
A: 

You may want to consider building a "You're about to leave this site" page instead. The idea is that you wrap URLs on the page that aren't on your site to point to that page, letting the visitor know they're about to leave, and giving them a chance to go back, or proceed.

It's gentler than an unexpected modal dialog, it lets you format your messaging better, and it ultimately gives your users the exact same choice.

Metal