Javascript 如何检测用户是否点击了“返回”按钮

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2008806/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 22:22:22  来源:igfitidea点击:

How to detect if the user clicked the "back" button

javascriptjqueryback-buttonjquery-events

提问by TIMEX

When the user goes history-back-1...how do I detect that? And then, alert "the user clicked back!"

当用户进入 history-back-1 时......我如何检测?然后,警告“用户点击了回来!”

Using binds (and jQuery preferably)

使用绑定(最好使用 jQuery)

回答by EricLaw

You generally can't (browser security restriction). You can tell if the user navigates away from the page (onbeforeunload, onunload fire) but you can't tell where they went unless you've set up your page to allow it.

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

HTML5 introduces the HTML5 History API; in conforming browsers, the onpopstateevent will fire if the user navigates back to an earlier "page" on your site.

HTML5 引入了 HTML5 History API;在符合标准的浏览器中,如果用户导航回您网站上较早的“页面”,将触发onpopstate事件。

回答by Adnan

try:

尝试:

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

回答by Mohsen Haeri

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

回答by Saurabh Ahuja

Following are the steps to detect back button click

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

  1. Register a mouse down event on body $('body').on('mousedown' ,'on all li' );

    2.Now set a variable when mousedown event occur.

    3.Check this variable when your location changes.

  1. 在身体上注册一个鼠标按下事件 $('body').on('mousedown' ,'on all li' );

    2.现在设置一个当mousedown事件发生时的变量。

    3.当你的位置改变时检查这个变量。

IF variable chages to true it means list cliked otherwise backbutton

如果变量 chages 为 true,则表示列表已点击,否则返回按钮

This work in my usecase .This solution may helps others because it depends on app design

这在我的用例中工作。这个解决方案可能会帮助其他人,因为它取决于应用程序设计

回答by Miranda

On the page you are looking at, you can add this piece of code to the onLoadevent to move them back the page they were on.

在您正在查看的页面上,您可以将这段代码添加到onLoad事件中,以将它们移回原来所在的页面。

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

If you want the alert then make it

如果你想要警报然后让它

if(history.length>0)alert("the user clicked back!")