JS to determine when the page cannot be rolled back (History.go (-1)), close the Web page

Source: Internet
Author: User

When making a Web project encounter a requirement, when the page has no precursor history (that is, the current is a new pop-up page, can not do GoBack operation is history.go (-1)), click the Back button to close the page directly, or return to the previous page.

The problem is how to determine whether there is a history can be rolled back, this is very troublesome, because no such function directly can be obtained, only through the history.length variable to do the work, but for IE, and non-ie length of the return value of different, ie: History.length=0, non-IE is 1, so write a function to implement the function required earlier. Share to 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); }    }}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.