Home >Web Front-end >JS Tutorial >js determines when the page cannot be returned and closes the web page, otherwise history.go(-1)_javascript skills
I encountered a requirement when working on a Web project. When the page has no previous history record (it is currently a newly popped-up page and cannot do the goback operation, that is, history.go(-1)), click the return button directly Close the page, otherwise return to the previous page.
The problem encountered is how to judge whether there is history that can be rolled back. This is very troublesome because there is no such function that can be obtained directly. The only way to do this is through the variable history.length. However, for IE, and non The return value of IE's length is different, ie: history.length=0, and non-IE's length is 1, so I wrote a function to implement the previously required function. Share it with everyone.
/** * 返回前一页(或关闭本页面) * <li>如果没有前一页历史,则直接关闭当前页面</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{ //非IE浏览器 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{ //未知的浏览器 window.history.go( -1 ); } } }