0

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.

Evgenij Reznik
  • 17,916
  • 39
  • 104
  • 181
  • Out of curiosity what is your intended use for this? An exit offer? – hopkins-matt Jan 12 '16 at 20:55
  • @hopkins-matt: I want to reset the form: all checkboxes, radio buttons etc. – Evgenij Reznik Jan 12 '16 at 20:57
  • 1
    You want to clear forms on backwards navigation? Why not just clear them anytime the page loads? – hopkins-matt Jan 12 '16 at 21:00
  • Will the link that users can click be an internal or external link? – hopkins-matt Jan 12 '16 at 21:02
  • @hopkins-matt: It will be an external link. – Evgenij Reznik Jan 12 '16 at 21:02
  • I've done tracking using cookies to track back navigation before, but that will still only work on internal links. The only think I can see working is resetting on page load. – hopkins-matt Jan 12 '16 at 21:04
  • If what you want is to clear the form values, how about cleaning the data [`onbeforeunload`](https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload) instead of when the user comes back? – Alvaro Montoro Jan 12 '16 at 21:08
  • The question is different but similar in this post. Take a look at the proposed solutions here: http://stackoverflow.com/questions/829046/how-do-i-detect-if-a-user-has-got-to-a-page-using-the-back-button – Daved Jan 12 '16 at 21:09
  • 1
    @hopkins-matt: Ok, I solved it with `$( window ).load(function() { ... })` now. It didn't work with just `$( document ).ready(function() { ... })`. Thanks. – Evgenij Reznik Jan 12 '16 at 21:09

2 Answers2

0

This isn't working because your javascript is not running on 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.

hopkins-matt
  • 2,763
  • 2
  • 15
  • 23
0

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.

Chris
  • 987
  • 6
  • 24