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;
     };
4

1 回答 1

0

正如您无疑了解到的那样,onbeforeunload它提供了一种简单地取消导航事件的方法(请参阅此答案以获得一个好的开始),但它并不总是在所有浏览器中都以您想要的方式工作(许多只是显示一个确认弹出窗口出于安全原因,无论您做什么)。如果您还没有,请先试一试;在您当前的代码示例中,我没有看到任何取消尝试,只是历史操作。

如果做不到这一点,使用哈希路由可能会有所帮助——最好是通过一个库来管理 URL 哈希作为唯一的视图路由(烘焙到 Angular、React 等中)并history为您推送更改。为模态状态提供一个唯一的 URL(根据我的经验通常不会这样做)意味着“返回”只会关闭模态而不是重新加载页面。

于 2017-07-19T19:32:23.277 回答