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:
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.
<html> <body onUnload="location.href='url.html');"> <a href="http://www.irt.org"> When you click this link, url.html is opened.</a> </html>