简体   繁体   English

检测用户何时单击后退按钮

[英]Detecting when user hits back button

I'm trying to detect when the user hits the "back" button in their browser. 我正在尝试检测用户何时在浏览器中单击“后退”按钮。

When clicking on the link and then getting back, nothing happens: 当单击链接然后返回时,什么也没有发生:

<script src="http://code.jquery.com/jquery-latest.min.js"
    type="text/javascript"></script>

<script>
$( window ).on( "navigate", function( event, data ) {
  console.log( data.state );
});
</script>

<a href="http://www.google.com">Link</a>

I was expecting a message in the log. 我期待在日志中显示一条消息。

When the user checks some checkboxes, then go to another page and then returns back, I want to reset the form, so that all checkboxes are empty. 当用户选中某些复选框,然后转到另一页然后返回时,我想重置表单,以便所有复选框为空。

This isn't working because your javascript is not running on google.com . 这不起作用,因为您的javascript不在google.com运行。 If you are on the page with your javascript and click the back button, you may see the console.log message for a split second, but it is a race between the browser loading previous page and the console loading your message that will determine if you see the message or not. 如果您使用的是Javascript页面,然后单击“后退”按钮,则可能会console.log看到console.log消息,但这是浏览器加载上一页和控制台加载消息之间的竞争,它将决定您是否看看消息与否。

I had the same problem. 我有同样的问题。 The best solution I found was to use a checksum in the initial post. 我发现最好的解决方案是在初始帖子中使用校验和。 You can then compare the checksum and see if it had been used before, if it was then you can reset everything. 然后,您可以比较校验和,看看以前是否使用过校验和,如果已使用过,则可以重置所有校验和。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM