如何检测用户是否点击了“后退”按钮

问题描述 投票:0回答:6

当用户返回history-back-1时...我如何检测到这一点?然后,提醒“用户点击了返回!”

使用绑定(最好是 jQuery)

javascript jquery back-button jquery-events
6个回答
29
投票

您通常不能(浏览器安全限制)。您可以判断用户是否离开页面(onbeforeunload、onunload 触发),但您无法判断他们去了哪里,除非您已将页面设置为允许这样做。

HTML5引入了HTML5 History API;在符合要求的浏览器中,如果用户导航回站点上较早的“页面”,则会触发 onpopstate 事件。


8
投票

尝试:

window.onbeforeunload = function (evt) {
  var message = 'Are you sure you want to leave?';
  if (typeof evt == 'undefined') {
    evt = window.event;
  }
  if (evt) {
    evt.returnValue = message;
  }
  return message;
}

5
投票
window.onpopstate=function()
{
  alert("Back/Forward clicked!");
}

0
投票

以下是检测后退按钮点击的步骤:

  1. 在 body 上注册鼠标按下事件
    $('body').on('mousedown', 'on all li');
  2. 现在在 mousedown 事件发生时设置一个变量。
  3. 当您的位置发生变化时检查此变量。

如果变量更改为 true,则表示单击了列表,否则返回按钮。

这在我的用例中有效。该解决方案可能对其他人有帮助,因为它取决于应用程序设计。


0
投票

在加载时或使用后退按钮时隐藏加载:

        jQuery(document).ready(function ($) {
            $.minicart.hideLoading();
        });
        window.addEventListener('load', function () {
            jQuery(document).ready(function ($) {
                $.minicart.hideLoading();
            });
        });
        window.onload = function () {
            $.minicart.hideLoading();
        }

-3
投票

在您正在查看的页面上,您可以将这段代码添加到

onLoad
事件中,将它们移回原来所在的页面。

if(history.length>0)history.go(+1)

如果您想要警报,请制作

if(history.length>0)alert("the user clicked back!")
© www.soinside.com 2019 - 2024. All rights reserved.