When working on a web project, we encountered a requirement. When the page has no predecessor history (that is, the page is currently a newly popped up, and we cannot do goback operation, that is, history.go(-1)), then directly close the page when clicking the return button, otherwise it will return to the previous page.
The problem encountered is how to judge whether history can fall back. This is very troublesome, because there is no such function that can be directly obtained, and it can only be processed through the history.length variable. However, for IE, the return value of length is different from that of non-IE. ie: history.length=0, non-IE is 1, so a function was written to implement the function required before. Share with everyone.
/** * Return to the previous page (or close this page) * <li>If there is no history on the previous page, 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 ); } } }