检测用户是否点击了“返回”按钮 - 手机浏览器

问题描述:

我有非常奇怪的要求。检测用户是否点击了“返回”按钮 - 手机浏览器

要求说:在商品详细页,当产品形象,在灯箱打开然后按压在手机,产品详细页面浏览器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

正如你毫无疑问学到的,onbeforeunload提供了一种简单地取消导航事件的方法(请参阅this answer以获得开始的好地方),但它并不总是按照您希望的方式在所有浏览器中运行(无论您做什么,许多浏览器都会显示确认弹出窗口,以确保安全原因)。如果你还没有,先给这个镜头一下;在当前的代码示例中,我没有看到任何取消操作的尝试,只是历史操作。

如果失败了,使用散列路由可能会有所帮助 - 最好通过一个将URL散列管理为唯一视图路径(烘焙成Angular,React等)的库,并将更改推送到您的history。给模态状态一个唯一的URL(这通常不会以我的经验完成)意味着返回将会关闭模式而不是重新加载页面。