js判斷當頁面無法回退時關閉網頁否則就history.go(-1)_javascript技巧

來源:互聯網
上載者:User

在做一個Web項目時遇到一個需求,當頁面沒有前驅記錄時(就是當前為新彈出的頁面,沒法做goback操作即history.go(-1)),點擊返回按鈕時直接關閉頁面,否則就退回到前一頁。

遇到的問題就是如何判斷 是否有history可以回退,這個非常麻煩,因為沒有這樣的函數直接能擷取到,只能通過history.length這個變數做變通的處理,但是對於IE,和非IE的length的傳回值不同,ie: history.length=0, 非IE的為1,因此寫了一個函數實現前面所需求的這個功能。分享給大家。

/** * 返回前一頁(或關閉本頁面) * <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 ); } } }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.