Disable backward and forward button using javascript

I was facing the same problem and searching for a solution. I got no exact solution, so i wrote my own code.

STEP 1: Before writing the code i analyzed what the browser shortcuts for moving through the history. The shortcuts of different browsers to move through the history are :

given in format keyboard shortcuts (its key value)

Mozilla Firefox

Backspace (8) – 1 page back throught the history

Alt + left arrow (37) – 1 page back through the history

Alt + right arrow (39) – 1 page forward through the history

Shift + Backspace (8) – 1 page forward through the history

Internet Explorer

Backspace (8) – 1 page back throught the history

Shift + Backspace (8) – 1 page forward through the history

STEP 2: To handle these events when the key is pressed, i used ‘onkeydown‘ event of the ‘body‘ [ because these shortcuts can be used in document layout only].

here is the code,

Explanation :

In this code i have used 2 bool variables bShiftflag,bAltFlag.

First i check whether the Alt key ot Shift key is pressed

if(event.altKey ==1) {
 
bAltFlag = true;
 
}
 
if(event.shiftKey==1)  {
 
bShiftflag = true;
 
}

After setting the flags. Let us check all those conditions

if(event.keyCode == 8 || (event.keyCode == 8 && bShiftflag == true) || (event.keyCode == 37 && bAltFlag == true) || (event.keyCode == 39 && bAltFlag == true) ){return false;} else {return true;}

this if clause returns false if any one of the shortcut event is occured or returns true. When false is returned the keydown event is not executed.

 

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>