Fire Event after Page Close or Redirected to other page

2.8k Views Asked by At

I have some problems with ASP.NET page cycle. I want to fire event when page is going to be closed or redirected to other page. I try to use Page_Unload() but it is going to be fire when page display and in any button click event it is firing Page_Unload(). I want only to fire event when page is going to be redirected or close. Then I have tried to use the Javascript function window.onunload(). Again, same problem: it is firing when the first page displays. Is there any way to solve this?

1

There are 1 best solutions below

0
On BEST ANSWER

Look into Jquery's .beforeunload property. Here is an example:

$(window).bind('beforeunload', function(){ return 'Click OK to exit'; }); 

Please note, beforeunload canot prevent a page from unloading or redirect it to another page for obvious reasons; it would be too easy to abuse. Also if you just want to run a function before unloading, try the following:

$(window).unload(function(){ alert('Bye.'); }); 

Finally, don't forget to referrence jQuery in your head tag by using:

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

The above gets you the latest version from the internet and saves you the trouble to download it, and of course you can do so optionally, but I am just trying to get your thing to work asap. Oh, I also found an example for you. Click here to see a page that calls a function before it closes. Hope this helps bud.