SoFunction
Updated on 2025-04-07

js prevents Backspace key from causing browser back

I encountered the problem of pressing the Backspace key to make the browser back in the project. I searched the Internet for several solutions but it was not ideal. So we gather the wisdom of everyone, learn from the strengths of all families, and summarize them as follows:

1. Define a method to block Backspace in public js

function banBackSpace(e){
 var ev = e || ;
 //Get event objects under various browsers var obj =  ||  ||  ||;
 //Press Backspace key if( == 8){
 var tagName =  //Tag name // If the tag is not input or textarea, block Backspace from if(tagName!='INPUT' && tagName!='TEXTAREA'){
  return stopIt(ev);
 }
 var tagType = ();//Tag Type //In addition to the following types, all input tags prevent Backspace from being blocked. if(tagName=='INPUT' && (tagType!='TEXT' && tagType!='TEXTAREA' && tagType!='PASSWORD')){
  return stopIt(ev);
 }
 //Input or textarea input box prevents Backspace if it is not editable if((tagName=='INPUT' || tagName=='TEXTAREA') && (==true ||  ==true)){
  return stopIt(ev);
 }
 }
}
function stopIt(ev){
 if( ){
 //preventDefault() method prevents elements from happening to default behavior ();
 }
 if(){
 //IE browser uses = false; to prevent elements from happening by default  = false;
 }
 return false;
}

The method comments are written very clearly, so I won't explain them too much here.

2. Call this method after the page loads

$(function(){
 //Implement the intercept of character code, keypress blocks these function keys  = banBackSpace;
 //Getting function buttons  = banBackSpace;
 })

Note:Key event triggering order: keydown -> keypress -> textInput -> keyup

There is a problem: After the select drop-down list is expanded, the keyboard event cannot be obtained. When pressing the Backspace key at this time, the browser will still fall back to history; solution: Change the select drop-down box to easyUI's combobox;

The above method of js prohibiting the Backspace key from causing the browser to backward is all the content I have shared with you. I hope you can give you a reference and I hope you can support me more.