JavaScript + onunload event - javascript

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

Related

Inconsistency with beforeUnload across different browsers

I'm attempting to run a function (that sends some fetch calls to an API) inside of a "beforeunload" event handler and the results are mixed. With Chrome it successfully runs my function if the user reloads the page or clicks a link for a different webpage, but it doesn't work if they close the tab. In Firefox the function only runs if they close the tab, but not in any other scenario. When I debug the beforeunload handler in the browser I can see the event handler clearly is triggered but the function inside doesn't always run. I suspect the function I'm trying to feed being async is part of the issue but I don't know why the results would be so inconsistent?
This is how I'm currently writing the event handler
window.addEventListener('beforeunload', async function(evt){
await exitChat();
});
I've also tried not using async/await. Let me know if seeing the exitChat() function code would help or anything else.
Edit: After a bit more debugging I can confirm that the issue, with Chrome at least, is that when the window is closed it can't make it through the entire exitChat() function in time before the page closes. So is there a way to force a delay in the unloading process?

Why IE10 fires beforeunload event when clicking on anchor element with javascript href and how to prevent it

In order to track when user leaves the page, we listen to beforeunload event. Everything works fine until user, that uses IE10, clicks on empty link (anchor) with javascript in href parameter instead of url. For example:
Empty link with JS in href
This case makes IE10 sometimes fire beforeunload event. Chrome/IE11 work fine (0 beforeunloads), while IE10 fires it from time to time, especially if you click it fast. Here is JSFiddle to try it.
Does anyone know why does it happen and how to fix it? I would be happy to remove/replace such anchors in mark-up, but it is impossible in my case.
Thanks.
Technically, IE10 may be considered correct to do so because you are unloading the page... kind of. If your link were:
<a href="javascript:'blah';">
Then you would end up on a new page with just the content 'blah'. This is how javascript: links work. void returns nothing (undefined), and when a javascript: link returns nothing then it does not replace the page contents.
A similar thing would happen, in theory, if the target resource is a download - the page would normally be unloaded but because the target is a download, the page does not change. And HTTP response of 204 No Content should also trigger this behaviour.
However, as you have noticed, this is undesirable behaviour and so it has become more common to see that the browser will not trigger an unload event until the page itself really is being unloaded. Unfortunately, this is a browser-level thing and outside your control, as far as I'm aware.
To my knowledge the only real fix for this would be to ensure you are properly preventDefaulting your click event.

Waiting event before closing window using onbeforeunload

Context :
I have developped an application which require authentification. This application uses events for dialoging with a server. When the server answer, some events are send to the client (UI).
Problem :
When the user close the page, it is necessary to make a logout on the server. With my architecture, it's easy to call a method which perform this logout. But i would like that the user show the logout progress before closing the webpage. In fact, i would like to close the webpage only when a specific event (for example : disconnection_success), is well received.
Moreover, it's verry important to not launcg another webpage because event is received on the first webpage when the logout is successfull. (Because dialog is done throw XMLHttpRequest)
Test :
I already do some test using onbeforeunload but it seems that is difficult to customize the popup.
Do you have some ideas to resolve the problem ?
BR
There are some issues with this, but you're on the right track. You're right in that you should use onbeforeunload because it is the only event that you can have triggered upon the closing of the browser window. (I know you can use onunload but at that point you have no time to do anything.) The issue here is how much code do you want to execute. The onbeforeunload doesn't allow you much time before it starts to unload the page.
BTW, there are two different scenarios with onbeforeunload:
If you return a string inside the onbeforeunload event, it creates the pop-up that you were referring to. The issue here is that with the pop-up, you won't have enough time to execute code
The other option is not returning anything. Instead, call your logout methods. This should give your code enough time to execute before closing
I actually had a question very similar to this and ended up solving it myself: How to logout during onbeforeunload/onunload using Javascript
In your question you state that you want to have a progress bar displayed when they log-out. This is impossible to do when the user closes the browser. At the moment they close their window, you have lost all control, except for in the onbeforeunload (and onunload but don't use this), and that is why your code needs to be executed there. With that being said, you could anchor your logout button (I'm assuming you have one on your application) and have it display the progress bar.
Just think about what could happen if you actually did have that kind of control - where you could pop up windows and progress bars when the user is trying to close their browser window. You could pop up anything and restrict the user from having any reliable functionality. That is why it was programmed that the onbeforeunload (and unload) events are the only ones possible to access the closing of a browser. These events have some pretty strict guidelines to them that prevent any kind of possible mis-use. I understand the problem you're having, I was there and it stinks, but I think that is your only option if you were going to use onbeforeunload.

onhashchange reloads page?

Is that correct? I was thinking it was just an event that fired when the page refreshed. I did a basic document.write and did i++ whenever onhashchange was triggered but it always is at 0 and i lose all my other vars and stuff. I also tried return false, but nothing.
Am i doing it wrong? Or is onhashchange supposed to reset the page? If so, can you stop it but still fire the callback?
No onHashChange merely fires whenever the # portion of a url is changed, this is client-side only and the page should not reload when doing so. document.write however can clobber your global variables.
If you need more help we'll need more to go on.
It looks like the problem is that Web Inspector is super buggy with this. For example, multiple console.log()s in a onhashchange rewrite the same console.log(). Also, i noticed that sometimes the console would just go completely blank when changing pages. I discovered it's bugginess when I put a timer on the page and noticed the timer was incrementing but the console was showing blank or misinformation.

window.unbeforeunload show div IE7 problem

Currently I am developing a web application for which I am using a pre-loader icon. What I want is that the pre-loader becomes visible every time the user navigates to another page or refreshes the page. So far I have the following solution:
window.onbeforeunload = function() { $("applicationdisabler").show(); };
For Safari and Firefox it works fine when the user clicks a link or refreshes the page. However in IE7 the div only becomes visible when the user clicks a link and NOT when the user refreshes the page.
The user can refresh the page by hitting F5 (on Windows) or any other possible way the browser provided.
Of course I have been looking for some workarounds already. The following code shows the alert in IE7, but the div still doesn't become visible.
window.onbeforeunload = function() { $("applicationdisabler").show(); alert("come on!"); };
The code of my div:
<div id="applicationdisabler"><img src="images/preloader.gif" /></div>
Hopefully someone can help me out.
You need to put the # before the id on the jQuery selector:
$("#applicationdisabler").show();
Why not use just use the onLoad listener instead? Although it would be slightly slower it should be more reliable.
Actually after a bit of looking around I'm not sure modifying the DOM makes any sense unless the onBeforeUnload handler returns false first - i.e. forces the user to stay on the same page.
As I understand it the onBeforeUnload event is fired just before the page is unloaded, so if you don't return false the browser will unload the page and DOM, and any JavaScript executed after that will be pointless.
That doesn't quite explain why JavaScript isn't executed properly in the onBeforeUnload function, but from what I've seen sites only use the window.alert or window.prompt dialogs to ask the user if they want to leave the site, and then often executing JavaScript if the user decides to stay.
Hence I'm guessing that some browsers may not allow DOM manipulation when this event is fired - since if the page is unloaded any DOM manipulation done is completely pointless.
So either:
Return false in your onBeforeUnload method, and then show your preloader (although this will stop navigation to the next page)
Use the onLoad event of the next page to show the preloader image instead
Also note: Opera versions 9.5 and below do not support this event (I'm unsure about later versions) but GMail does manage to catch the back button in Opera.
Possibly related is this security warning for IE7's implementation of the onBeforeUnload event - it's possible Microsoft patched it in a way that prevents the things you're trying to do. And I know IE6 and below don't allow commands like document.location='' in the onBeforeUnload handler for security reasons.

Categories

Resources