Q:

Javascript To Get An Alert To Redirect When Closing The Browser Window

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:

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

Don't do this.
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.
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.

