[Javascript] Can this be done?

Ben Curtis Quixote at LaMancha.org
Thu Jun 21 11:40:16 CDT 2001


> Is there a way to have a script in a page that when the person either shuts
> the browser down or leaves for another URL that it will pop up a small
> window with a parting message...

First off, make sure that you aren't doing this to encourage them to come
back. They've already decided they want to leave and by popping up a window
you are essentially the door-to-door salesman who, when told to leave,
wedges his foot in the door so it can't be closed. You are hardly making a
good impression.

That said, I can think of a number of valuable reasons to do this.

What you want to do is open a window onunload of the page, but not if they
are following a link or form on the page. So, this little code should (in
theory -- I leave the testing to you) do the trick for you:

<head>
<script>
var Loaded,WinOK;
function deactivateWindow() {
  WinOK = 0;
  return true;
}
function addDeActivation() {
  Loaded = WinOK = 1;
  for (var xx=0; xx<document.links.length; xx++)
    document.links[xx].onclick = deactivateWindow;
  for (var xx=0; xx<document.forms.length; xx++)
    document.forms[xx].onsubmit = deactivateWindow;
}
function launchWin() {
  window.open('dont_go.html','byeWin','height=200,width=200');
}
</script>
</head>
<body onload="addDeActivation();"
onunload="if(Loaded && WinOK)launchWin();">



What does it do?
1) after the page loads, it sets some flags that say "the page is loaded"
and "opening a window is OK"
2) then it loops through all the links on the page and adds (actually,
overwrites) the onclick handler; then it does the same for all the forms,
adding it to the onsubmit
3) if a link is clicked or a form submitted, the WinOK flag is turned off
4) if the page unloads and the WinOK flag has not been turned off, a window
pops up.

+Ben Curtis

"One of the symptoms of an approaching nervous breakdown
is the belief that one's work is terribly important."
- Bertrand Russell (1872-1970)










More information about the Javascript mailing list