faqts : Computers : Programming : Languages : JavaScript

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

86 of 142 people (61%) answered Yes
Recently 8 of 10 people (80%) answered Yes

Entry

How can I detect if a user hit the browser's back button?

Apr 4th, 2008 21:13
ha mo, Yuriy Fuksenko, Colin Fraser, Jeff Lynch,


At this time Javascript is unable to trap the back button in the parent 
window. However, you can use : 
<script language="JavaScript"><!--
 function othergo(there) {
     if (document.images)
         location.replace(there);
     else
         location.href = there;
 }
 //--></script>
 <a href="somepage.htm" 
onClick="this.href='javascript:othergo('http://www.gothere.com/apage.htm
')'">go there</a>
Replace() will work in Opera, but only if you use absolute URL's.
I think I found a way to get back button information, using JavaScript, 
so you can handle back button, if you need to, by showing a warning or 
running some JavaScript function, or even reloading a page.
My code is taking advantage of the fact, that if page is coming from 
browser cache and not hitting a server (for NS, even if it hitting 
server, but back button or reload was used),  browser will try to 
preserve previous values for a form fields. I didn't give it whole 
bunch of testing, but I tried this code with IE6.0 and NS7.0 - it 
worked in both cases. 
Here is the code:
After you load a page, hit the "is back button" button. Then go to some 
other URL, and then come back and hit "is back button" button again.
<HTML>
<BODY ONLOAD="handleBackButton()">
<FORM NAME="_mine">
<INPUT NAME="_a1" VALUE="1" STYLE="visibility:hidden">
</FORM>
<SCRIPT LANGUAGE="JAVASCRIPT">
var x="1";
var isBack;
function handleBackButton(){
   isBack = (x != document._mine._a1.value);
   document._mine._a1.value=2;
   document._mine._a1.defaultValue=2;
}
function isBackButtonUsed(){
 return isBack;
}
</SCRIPT>
<H1>Back button testing</H1>
<form>
<input type=button value="is back button" onclick="(isBackButtonUsed())?
alert('Back button was used'):alert('Page was loaded normally')">
</form>
</BODY>
</HTML>
http://www.businessian.com
http://www.computerstan.com
http://www.financestan.com
http://www.healthstan.com
http://www.internetstan.com
http://www.moneyenews.com
http://www.technologystan.com
http://www.zobab.com
http://www.healthinhealth.com