Home Articles FAQs XREF Games Software Instant Books BBS About FOLDOC RFCs Feedback Sitemap
irt.Org
#

Q257 How can I detect when a visitor is leaving my site?

You are here: irt.org | FAQ | JavaScript | Misc | Q257 [ previous next ]

Its going to be extremely difficult to do this. The user can leave your site for one of several reasons:

  1. They can click a link
  2. They can close the window
  3. They can type in a URL in the location field
  4. They can pick an entry from their bookmarks

The only one you can trap with any certainty is the first one, when the visitor clicks a link. If a link on your site looks like:

<A HREF="http://www.yahoo.com/">Go to Yahoo</a>

Then its a link out of your site. You can change this in several ways:

<A HREF="http://www.yahoo.com/" onClick="functionName()">Go to Yahoo</A>

When the link is clicked the onClicks event handler will invoke the functionName() function, which you can then use to do whatever you like before the event handler returns control back to the link which then goes to Yahoo. This option is browser safe - i.e. it'll still enable the user to go to Yahoo even if their browser does not support JavaScript, or even if they've turned off JavaScript. It just won't invoke the functionName() function.

Or you could change it as follows:

<A HREF="javascript:functionName('http://www.yahoo.com/')">Go to Yahoo</a>

This replaces the normal link to Yahoo with a link to a JavaScript function which you can then use to change the documents location:

<SCRIPT LANGUAGE="JavaScript"><!--
function functionName(url) {
    // test to see if the url has a http: in it:
    if (url.indexOf('http:') >-1 ) {
        // absolute url, potential external link
        // test to see if its within my site
        if (url.indexOf('www.mysite.com') > -1) {
            // phew !
        }
        else {
            // external so say goodbye
            // put your own code here
        }
    else {
        // relative url, therefore within site
    }
    // now go to url
    location.href = url;
}
//--></SCRIPT>

The following was submitted by KongGeo aka KoGeee

There is something called <body onUnload=""> in IE. It will capture when people write an address in their addressbar, and when people click any link.

&lt;html&gt;
&lt;body onUnload="location.href='url.html');"&gt;
&lt;a href="http://www.irt.org"&gt;
When you click this link, url.html is opened.&lt;/a&gt;
&lt;/html&gt;

©2018 Martin Webb