简体   繁体   中英

JavaScript + onunload event

I want to fire onunload event to do some clean up operations, I have multiple tabs(Navbar) showing multiple links to different web pages,my problem is that even when I'm in some other page my unload function which is in tag of some other jsp is fired. Please help to resove this, I want unload function to be called when user closes browser in that page.

I'm not sure how you got the onunload event to work....The problem I've found with using the onunload event is that it is fired after the page has been unloaded. This means that no more JavaScript can be executed because the page has been unloaded.

You should be looking into using the onbeforeunload event. This event is a little unique because if the function that handles this event returns anything a pop up is displayed asking the user if they would like to continue with the operation. So, in your case make sure that your function doesn't return anything. The other thing to note about the onbeforeunload event is that, at this time, Opera does not support it (Safari, FireFox, and Internet Explorer do though).

Both the onbeforeunload and onunload events are executed every time the page is unloaded. If a control on your page submits the page to the server code, the page is unloaded and the JavaScript is executed.

If you don't want the JavaScript to be executed when a control on your page is submitting it to the server you have to implement something that checks to see whether or not your code should be executed.

This is simple, add a JavaScript boolean to the page and a function that set's this boolean to true. Make sure that every element in your page that posts back to your server code sets this boolean to true before it submits the page. Check this boolean in your onbeforeunload event to see if your cleanup code should be executed.

Hope this helps,

-Frinny

It seems that the unload function has been created in a global scope. Try placing that function only on the page you want to act.

You have a frameset page? And you want to be notified when they navigate away from the frameset? Add an onbeforeunload on the frameset. I don't know what you mean by clean up, but you can't send XHRs during unload safely across browsers

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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