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?
Related
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.
I have a website with master page. I want to catch a user trying to close the browser/tab. When I try using onunload in the body tag, it fires not only when I try closing the browser, but also when I navigate to another page.
Any idea how to only catch the event of closing the browser?
That is not possible. Javascript can only determine if the page you're on closes. If Javascript could determine whether other tabs and windows you're on closed, for example knowing if you closed down Facebook or Flyspray, that would be a major security risk. That's now how javascript works.
I am working with a secure wizzard online, that will save data through the process, and I needed to detect wether the client closed the tab and/or the browser, so far everything was going allright until I clicked the "continue" button to proceed to the next step, it threw me the same message, I've done quite some research on this and there is no way I'll be able to ignore the unload event that occurs when I navigate away from the pagethrough a link.
I tried to use the
if(window.event.clientY < 0 && window.event.clientX < 0){
alert('holy damn! the window is closing!')
};
and some other methods that are around the web. none of them will be able to detect only the browser closing. So as far as my research has advanced, there is no way to do this.
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!
How can we detect when a user opens a new window. The user is already authenticated and we make heavy use of sessions.
We were trying to avoid Ctrl+N javascript hooks but maybe that is an option.
I am assuming the request is the exact same URL...with Ctrl+N?
We were trying to avoid ctrl-n javascript hooks
Forget it. Whilst you could in theory try to catch keypress events for ‘n’ with the Control key modifier, there are any number of other ways to open a new window or tab which may be more likely to be used, and you won't be able to catch. File->New Window/Tab, middle click or shift-click link, middle click back/forward buttons, right-click-open-in-new-window, open bookmark in new tab, double-click browser icon...
The user is already authenticated and we make heavy use of sessions.
That shouldn't be a problem in itself. I guess what you mean is that your application is dumping all sorts of page-specific data in the session that it shouldn't have, and now you find the application breaks when you have more than one window open on it? Well, commiserations and happy rewriting.
In the meantime about all you can do is tell the user “please don't try to open two browser windows on the same application”. There are potential ways you can make JavaScript on one page notice that JavaScript is running on another page in the same domain at the same time, generally involving using document.cookie as a inter-page communications conduit. But that's also a bit fragile.
If opening a new window causes a problem in your application, then you should fix the application code to handle it instead of trying to apply an inconsistent and unreliable client-side "bandage". That's my opinion.
Why?
And anyway you can't detect it. User can open new window not only with Ctrl+N but also with File->New Window.
You could possibly put a window count into the session and increment it on window.onload and decrement it on window.onunload.
Imagine me tutting, sucking air through my teeth and going "better you than me, guvna" if you use that, though.
What I have done to solve this issue is when the user authenticates set the window name on valid login.
<script>
window.name = 'oneWindow';
</script>
And then on the master page do a javascript check:
<script>
if (window.history.length == 0 || window.name != 'oneWindow')
//history length to see if it's a new tab or opened in a new window 0 for IE, 1 for FF
//window name to see if it's a CTRL + N new window
</script>
If the check is true then hide/remove the main content of the page and show a message stating they are doing something unsupported.
This works when your login page is not tied into the master page.
If you do not have a master page then I would suggest putting the check on all your pages.
Yes and no,
You'll always see it if a control has focus, else the event is sent directly to the browser and the code on the page never hear about it.
In my experience you can't hijack the browser's shortcut, your mileage may vary. You are likely to know it happened but the browser will do its thing (for obvious reason)
In most browsers, the effect of Ctrl-N is to open a new window at the same URL as the old one and associate it with the same sessionID.
Your best bet would be to modify the back end code if possible and allow for such things. Breaking the browser's feature is never a good thing.
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.