Waiting event before closing window using onbeforeunload - javascript

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.

Related

javascript/jquery - crossbrowser detection when user is closing the browser?

i'm looking for a reliable way on how to detect when a user closes the browser/tab in order to display a warning message (i'm having a shopping cart which uses sessions).
i've googled and couldn't find a proper solution - window.onunload will display a message every time i'm refreshing the page ..
any ideas?
thanks
You can't tell the difference between closing, reloading, back/forward etc.
beforeunload is fired on all of them.
Depending on if you launched the window yourself, you could run your code before calling window.close(), but this won't be called if the user closes the window themselves.
I don't believe such a thing is possible.
The browser can fire an event when the page (un)loads, but who's to say wether the user is navigating, or closing the browser/tab?

window .open is not opening on page load in ie8

Hi unable to open window.open on page load in ie8 If I use window.location its not opening in new page please help me out of this.
This is because you're running into the popup blocker. This is a Good Thing(tm) :-) You can only open popups in response to the user taking an explicit action, like clicking something (and then typically only from within the event handler itself), not on things like page load where the unwitting user could be (and historically has been) inundated with dozens of windows opening all over the place. (And even doing it in response to an explicit user action may not be allowed by some blockers.)
Are no-one seeing a big problem with running window.open(window.location.href,'_blank') in the onload handler?
This is systematically a recursive function which would continue until the user manages to close the new window prior to the onload handler running.
I'm not saying that this has anything to do with the problem it might just be that IE8 is clever enough to see this..

How distinguish refresh and close event using jQuery? [duplicate]

This question already has answers here:
Identifying Between Refresh And Close Browser Actions
(13 answers)
Closed 6 years ago.
I am currently looking at the "unload" event of a window to try to determine how the "unload" event was triggered, but am having little success. Is there a way to determine how the javascript event was triggered?
Page Refresh
Back Button (or navigate away from the page)
Closing the Browser
Essentially I need to execute some code only when the browser window is being closed, not refreshed or navigated away from.
Purpose: When a customer does an update of our software, the update will redirect their first Internet request to an offer page. There is a button for a "Do Not Bother" option, but some users will simply close their browser. Upon closing the browser, I need to duplicate the "Do Not Bother" functionality so the user no longer gets redirected to the offer page. Simply attaching to the "unload" event will not work due to the different ways of leaving a page.
No, and if there was it would be browser dependent.
What kind of code are you trying to run when the user closes the page?
Is it to logout the user?
Then the user would not be logged out if the browser crashes or the network connection breaks (and probably not if the computer goes to sleep/hibernation mode).
If it is for logout-purposes you should probably use a timestamp variable at the server that gets updated with every request (or use a ajax-ping), and logout the user if it hasn't been seen for a specified time.
Update: Found this answer here at stackoverflow.
Yes, there is a solution!
I've designed a solution based on onBeforeUnload+onLoad events, HTML5 local storage and client/server communication. See the details on https://stackoverflow.com/a/13916847/698168.
I use a method of doing keyboard "sniffing", in that it looks for keydown's of "F5", "ctrl+r", "alt-f4", "backspace" and others, and if it finds them flowing through the keyboard event queue, it sets boolean variables appropriately to trap that status... then I use a "onbeforeunload" function handler, which tests against those boolean status variables to decide what to do.
You can even shut down various keyboard strokes (like "ctrl+n" or "F1" for instance) by using preventDefault(), bubbles=false and returnValue=false in your keyboard handling.
This stuff is not for the faint of heart, but its certainly doable with some persistence and lots of cross browser testing!

Jquery Effect Onunload

I would like to use the jquery slideUp effect when the user navigates away from the page just to make the page look cool as it closes.
I assume that I should use the onunload event but how can I delay the page closing long enough for the effect to run to completion.
One of the options that came to mind is effectively hijacking the page closing function, storing it in some variable and then executing it once I had run my effect but I have no idea how I would do that.
Any suggestions or alternative ideas are more than welcome
what you're looking for is the onbeforeunload event.
just a warning though... it should be really quick... or your visitors are probably going to hate it no matter how cool it looks
as to preventing the page from navigating away before the animation is done, that's a bigger problem... any animation is going to rely on setTimeout/setInterval and the page won't wait for those to complete before leaving.
Doing anything but closing the window when the users ask to is breaking a contract with the user. The browser window is not yours, it's the users, and no matter how cool the effect, it will inevitably annoy most of your users.
The onbeforeunload event is very restricted in what it can do. It must return a string, which is then used to prompt the user for a confirmation about leaving the page. It won't work for cool animations.
As far as I know, the only way to stop a user from leaving a page is the onbeforeunload event, which isn't cancelable. Instead, you return a string from that method, the browser prompts the user with a Yes/No dialog, life goes on. 276660 has more info about this.
I don't think you're going to have much luck with this one.
why not, instead of making a "cool" effect when a user simple want to go away from your website (even if the user closes the browser/tab the unload event will be fired) and annoying the simple user with that ... preventing him/her to return again...
...do that "cool" effect when a user reaches your website for the first time? as a normal intro effect?
I did that as a simple idea, you can see it here: http://www.balexandre.com/jmfc
I would agree 100% with Jonathan Fingland's answer, and add this.
In IE, (I'm not sure what versions support this, I know IE6 did) you can use some propriety meta tags to achieve fades etc when leaving the page. However, this is limited in browsers (IE only), so you're stuck for cross browser use.
You may find loading new content via AJAX would give you better control of effects and transitions, as well as reducing the annoyance factor to the user which can result from trying to hijack the browser actions in such a manner.
I would look at using a form of slider as mentioned above (see for instance http://webdesignledger.com/tutorials/13-super-useful-jquery-content-slider-scripts-and-tutorials),
or simply loading content panes in response to user clicks.
The only way I've found for delaying the window to close, is using an alert. If this is an acceptable compromise for your case, it will really delay the window destruction in memory, and allow your page timers to execute (of course, if user does not close the alert popup earlier than your animations finalize).
I recently used this approach so i could call a flex method through FABridge (which would otherwise be destroyed before the flex method call finishes). I'd like to hear your comments on this.

How do I know when the browser is being closed?

I am writing an ASP.NET application that tracks the user's scores and info (it is a
training application) to an access database, if any one closes the browser directly I want to display an alert message.
My problem is that I cannot use the unload event because When I pressed any ASP.NET button at that time unload event occurs. What event should I be using that will work for IE and FF?
I want to handle event Browser close(X).
The onbeforeunload event will only give you the confirm box with a message. You can't put more functionality into it.
What you should be doing is having both the window unload eventhandler and the logout button click eventhandler call the same logout method. You don't need to stop the user and ask them to press your button, your button should be just another way of doing the same thing.
Also: have you considered SCORM?
Not sure you know what you want to do here. ;-)
Do you want to prevent the user completely from closing the browser until a certain point in the trainig? If so, have you considered using a modal and maximized window? You should be able to maximize the window without the titlebar, buttons and menus.
Or if you just want to keep track of the progress, scores or similar, then you could use cookies handled by the browser via JavaScript. Just bear in mind that this will keep the data on just one machine for the student.
If you just want to warn the user that he is about to leave the training course, you could use onbeforeunload
I think others have adequately answered your specific question, but Tooney raises some good points. To expand on these. Where are you currently maintaining your the state? Are the scores stored in cookies, within a server-side session or do your persist them page by page within the database.
Assuming this isn't a cheap and cheerful solution, then I would suggest you consider persisting results page by page, as it is minimise the loss of information caused by a premature exit (either by design or accident). Of course, you then need a process to cleanup incomplete training session.
You could still use the onbeforeunload function to trap user exits, but personally I don't like UI's that double check users actions.
Good luck.

Categories

Resources