2016-09-16 90 views
2

我有非常奇怪的要求。檢測用戶是否點擊了「返回」按鈕 - 手機瀏覽器

要求說:在商品詳細頁,當產品形象,在燈箱打開然後按壓在手機,產品詳細頁面瀏覽器back按鈕將顯示,沒有前一頁即產品網格頁面

所以,我想過如何在跨瀏覽器中處理返回按鈕。一些解決方案在桌面瀏覽器中工作,但沒有在Mobile Browsers

工作,我嘗試以下解決方案:

window.onload = function() { 
if (typeof history.pushState === "function") { 
    history.pushState("jibberish", null, null); 
    window.onpopstate = function() { 
     history.pushState('newjibberish', null, null); 
     // Handle the back (or forward) buttons here 
     // Will NOT handle refresh, use onbeforeunload for this. 
    }; 
} 
else { 
    var ignoreHashChange = true; 
    window.onhashchange = function() { 
     if (!ignoreHashChange) { 
      ignoreHashChange = true; 
      window.location.hash = Math.random(); 
      // Detect and redirect change here 
      // Works in older FF and IE9 
      // * it does mess with your hash symbol (anchor?) pound sign 
      // delimiter on the end of the URL 
     } 
     else { 
      ignoreHashChange = false; 
     } 
    }; 
    } 
}; 

也試過這樣:

if (window.history && window.history.pushState) { 

$(window).on('popstate', function() { 
    var hashLocation = location.hash; 
    var hashSplit = hashLocation.split("#!/"); 
    var hashName = hashSplit[1]; 

    if (hashName !== '') { 
    var hash = window.location.hash; 
    if (hash === '') { 
     alert('Back button was pressed.'); 
    } 
    } 
}); 

試過這個問題,以及

window.onbeforeunload = function (e) { 
     var e = e || window.event; 
     var msg = "" 
     $("#blueimp-gallery").hide(); 
     // For IE and Firefox 
     if (e) { 
      e.returnValue = msg; 
     } 

     // For Safari/chrome 
     return msg; 
    }; 
+0

您的瀏覽器需求是什麼? history.pushState適用於除Opera Mini以外的大多數移動瀏覽器。 – SchattenJager

+0

所有手機瀏覽器。我真的不關心Opera。如果您認爲它在所有瀏覽器中都可用,那麼我應該如何通過按回按鈕來隱藏燈箱,然後在關閉燈箱後按鈕應該表現爲默認行爲 – Gags

回答

0

正如你毫無疑問學到的,onbeforeunload提供了一種簡單地取消導航事件的方法(請參閱this answer以獲得開始的好地方),但它並不總是按照您希望的方式在所有瀏覽器中運行(無論您做什麼,許多瀏覽器都會顯示確認彈出窗口,以確保安全原因)。如果你還沒有,先給這個鏡頭一下;在當前的代碼示例中,我沒有看到任何取消操作的嘗試,只是歷史操作。

如果失敗了,使用散列路由可能會有所幫助 - 最好通過一個將URL散列管理爲唯一視圖路徑(烘焙成Angular,React等)的庫,並將更改推送到您的history。給模態狀態一個唯一的URL(這通常不會以我的經驗完成)意味着返回將會關閉模式而不是重新加載頁面。

相關問題