4

Possible Duplicate:
Best way to detect when user leaves a web page

How can I call a javascript or jQuery function when back button of browser is clicked? I have seen some solutions but none of them worked for me. Can anybody show me some example code?

Hamid Mohayeji
  • 3,977
  • 3
  • 43
  • 55

3 Answers3

9

In jQuery try this :

$(window).unload( function () 
{
// put your code here
});

In javascript :

window.onbeforeunload = function () {
   // put your code here
}
Niklas
  • 13,005
  • 23
  • 79
  • 119
senthilbp
  • 807
  • 1
  • 9
  • 16
1
<body onUnload="yourFunction();>
<!-- ... -->
</body>
Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
0

You can use history.replaceState() (see browser support) to modify the previous URL you visited to the current page with an added parameter of your choosing like for instance redirect=<URL of previous actual previous page> (you can maybe get this URL from the referer?), then detect the parameter in document ready and perform the required actions.

This is just an untested theory, I might elaborate later on when I get to test it.

ohaal
  • 5,208
  • 2
  • 34
  • 53