Easy Java Script Code to Disable the Browser Back Button
The code
Before we discus how to append the index to the URL string, we first need to discus
how to retrieve the index from the URL string. Below is an example of a variable
appended to a URL string. In this case the name of the variable is "p" and it's value is 8.
http://www.domain.com/page2.htm?p=8
In Java Script we access the URL string through the document's location object
and use a few string object methods to extract the value, as shown below.
var strLoc = document.location.href;
var i = strLoc.indexOf("=");
var p = strLoc.substring(i + 1,strLoc.Length);
If you want to follow along with the example, open your favorite ASCII text editor,
such as Windows Notepad. Create a webpage that represents an outside webpage where
the user clicked on a link that brought them to your Web site. The code for this
is shown below. Type this code into Windows Notepad and save the file with the
name "outside.htm".
<html>
<head>
</head>
<body>
<a href="page1.htm">To Your Page 1</a><br>
<a href="page2.htm">To Your Page 2</a><br>
<a href="page3.htm">To Your Page 3</a>
</body>
</html>
Start a new document in Notepad and create the first page for your Web site. The
code for this is shown below. Enter this code into Windows Notepad and save the
file with the name "page1.htm".
<html>
<head>
<script language="JavaScript">
var strLoc = document.location.href;
var i = strLoc.indexOf("=");
var p;
if(i == -1)
{
location.href="page1.htm?p=0";
}
else
{
p = strLoc.substring(i + 1,strLoc.Length);
p++;
}
</script>
</head>
<body>
This is page 1
</body>
</html>
When the user first arrives at your Web site, the URL does not have the index
appended, therefore the indexOf method can't find "=" in the string so it will
return -1. In the code above, if the URL does not have the index appended,
the code above adds the index to the URL string. If the URL already has the
index appended, the code extracts it's value and increments it.
We will have three pages in this Web site, so enter the code shown below into
the body section of the webpage. This code creates links to the other two pages
with the incremented value of the index appended.
<script language="JavaScript">
document.write("<a href='page2.htm?p=" + p + "'>page 2 </a><br>");
document.write("<a href='page3.htm?p=" + p + "'>page 3 </a><br>");
</script>
All three pages will contain similar code. In operation, each time the user
visits a page on your Web site, the value of p is incremented. If they use the
Back button, the URL retrieved from the browser's history list will have the
original (lower) index value attached. Now let's create a function that disables
the Back button when the index is "1". The code for this is shown below.
function noExit()
{
if(p == 1) history.go(1);
}
|