Js determines if the page cannot be retraced to close the page otherwise history.go of 1

  • 2020-03-30 03:38:52
  • OfStack

When I was working on a Web project, I met a requirement. When the page has no previous history (that is, the page currently pops up, so I cannot do the goback operation, namely history.go(-1)), I will close the page directly when I click the back button, otherwise I will return to the previous page.

Problem is how to determine whether there is the history can back, this is very troublesome, because there is no such a function can get directly, only through the history. The length of the variable do alternative processing, but for Internet explorer, and the length of the return value is different, IE IE: history. The length = 0, the IE is 1, so write a function to realize the above requirements of the function. Share it with everyone.


/** 
*  Return to previous page (or close this page)  
* <li> If there is no previous page history, close the current page directly </li> 
*/ 
function goBack(){ 
if ((navigator.userAgent.indexOf('MSIE') >= 0) && (navigator.userAgent.indexOf('Opera') < 0)){ // IE 
if(history.length > 0){ 
window.history.go( -1 ); 
}else{ 
window.opener=null;window.close(); 
} 
}else{ //Non-ie browser
if (navigator.userAgent.indexOf('Firefox') >= 0 || 
navigator.userAgent.indexOf('Opera') >= 0 || 
navigator.userAgent.indexOf('Safari') >= 0 || 
navigator.userAgent.indexOf('Chrome') >= 0 || 
navigator.userAgent.indexOf('WebKit') >= 0){ 

if(window.history.length > 1){ 
window.history.go( -1 ); 
}else{ 
window.opener=null;window.close(); 
} 
}else{ //Unknown browser
window.history.go( -1 ); 
} 
} 
}

Related articles: