javascript 如何在 Chrome、Firefox 和 IE 中捕获返回按钮事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29937643/
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-10-28 11:21:26  来源:igfitidea点击:

How to capture back button event in Chrome,Firefox and IE

javascriptjqueryhtml

提问by user2078643

I have to capture if user clicks on back button of browser(IE, Chrome and Firefox)

如果用户单击浏览器(IE、Chrome 和 Firefox)的后退按钮,我必须捕获

I don't want onbeforeunloadevent to be called when user presses the back button of browser

我不想在用户按下浏览器的后退按钮时调用onbeforeunload事件

回答by Tushar

UpdateIn the following function when u click on links you will see the event being fired....now after clicking on any link click back button youll agin c the event being fired.

更新在以下功能中,当您单击链接时,您将看到正在触发的事件....现在单击任何链接后单击返回按钮,您将看到正在触发的事件。

JSFiddle

JSFiddle

$(window).bind( "hashchange", function(e) {
  alert()
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://github.com/cowboy/jquery-bbq/raw/v1.2.1/jquery.ba-bbq.min.js"></script>

<nav id="siteNav">
<ul>
<li class="nav1"><a href="#landing" title="Home">Home</a>
<li class="nav2"><a href="#products" title="Products">Products</a>
<li class="nav3"><a href="#about-us" title="About Us">About Us</a>
<li class="nav4"><a href="#sign-up" title="Sign Up">Sign Up</a>
<li class="nav5"><a href="" title="Videos">Videos</a>
</ul>
</nav>

Use the hashchangeevent:

使用hashchange事件:

window.addEventListener("hashchange", function(e) {
  // ...
})

回答by Andrea Giachetto

I was looking for the same thing a while ago, but the Back button event of the browsers cannot be listened to. But, if it could be handy, you can use jQuery (or Javascript) and use the .unload() method

前段时间我一直在寻找同样的东西,但是无法监听浏览器的后退按钮事件。但是,如果方便的话,您可以使用 jQuery(或 Javascript)并使用 .unload() 方法

Jquery .unload() API

Jquery .unload() API