9

My webpage runs a javascript function when the page is loaded. However, I don't want the function to run if the user comes back to this page using the back button. How can I prevent this using javascript?

$(document).ready(function(){
  // Do not run this function if the user has arrived here using the back button  
  RefreshThePage();
});
Tom
  • 1,047
  • 4
  • 15
  • 27
  • possible duplicate of http://stackoverflow.com/questions/55871/track-when-user-hits-back-button-on-the-browser – T.J. Crowder Mar 30 '10 at 14:35
  • Duplicate: http://stackoverflow.com/questions/55871/track-when-user-hits-back-button-on-the-browser At least one better answer here, though, question should be merged but not deleted. – T.J. Crowder Mar 30 '10 at 14:36
  • I have same problem right now, can you share how did you solve this problem? – Agung Setiawan Sep 01 '14 at 15:10

4 Answers4

4

I'd have thought that using cookies is the easiest way to do this

matpol
  • 3,042
  • 1
  • 15
  • 18
0

I think studying the way Struts handles duplicate form submissions could help you.

Some links:

http://www.techfaq360.com/tutorial/multiclick.jsp

http://www.java-samples.com/showtutorial.php?tutorialid=582

http://www.xinotes.org/notes/note/369/

thelost
  • 6,638
  • 4
  • 28
  • 44
0

Track when user hits back button on the browser

There are multiple ways of doing it, though some will only work in certain browsers. One that I know off the top of my head is to embed a tiny near-invisible iframe on the page. When the user hits the back button the iframe is navigated back which you can detect and then update your page. Here is another solution.

You might also want to go view source on something like gmail and see how they do it.

Here's a library for the sort of thing you're looking for by the way

Community
  • 1
  • 1
Haim Evgi
  • 123,187
  • 45
  • 217
  • 223
-4

The event object offers you to get the key code. so basically you register an eventlistener onKeyDown. Use the received event. if the keycode matches the key you like continue with your function.

document getElementById('elementId').onKeyDown = checkKey();
function checkKey(event) {
  if (event.keyCode === keyCode) then . . . 
}

play around with alert(event.keyCode); to find the right one.

  • 3
    Tom is referring to the browser's Back button, not a back button in the page. And I don't think you can capture the browser's back button as a keyboard event in JavaScript. – Prutswonder Mar 23 '10 at 09:50