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.
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'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?
I have an application which had developed according to IE6.
Now Because of IE8 tabbing features not the application have been start giving problem.
The Problem is that,
if I have opened first context in "tab1" and then open second context in "tab2".
Now when I back to "tab1" and refresh the page then it loads the second context that is new one.
This is logically correct but I want to block the user while opening the second tab so that user restrict to only first tab.
So I have been come to conclusion that we can do this with JavaScript by getting some tab event, but I am not too much familiar with JavaScript.
Please tell me is there any solution if you have in your mind for above problem,
or tell me is there any way so that we can catch the tab event.
Praise all things glorious: There is no way to prevent a user from opening a new tab. In Firefox, you can cruelly prevent a user from using keyboard shortcuts to open a new tab by returning false from an input element's onkeypress event, but it's still possible to open a new tab otherwise.
The solution? Well, from what you're saying, it sounds as though you're using the session to store the user's current page (and, well, most everything else, but that's another story). Having spent a lot of time using a web application that was built that way, I can tell you firsthand: don't do this! The web already has a wonderful method for storing the user's current page: the URL.
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.
This question already has answers here:
Identifying Between Refresh And Close Browser Actions
(13 answers)
Closed 6 years ago.
After being through numerous forums available on the net for last 5 days, I am still not able to completely track down the browser close event. My requirement is to generate a popup message, when user tries to close the browser.
I have called my javascript function on body 'onbeforeunload' event. And I have hardcoded the conditions to check the mouse-coordinates for the red 'X' buton of browser, refresh, File-close or Alt-F4.
My code works fine when browser window is Maximized, but fails if we shrink it after a limit. Please help me, if some body has already found the solution to a similar problem.
Thank you.
Aggregated Responses of OP
------
Ok, just tell me if it is possible to detect if a user has clicked on the Refresh button of the browser. Also, Refresh can be triggered by Right-click - Refresh or Ctrl-R. My requirement is to make a variable false on Refresh. I am just able to do it on F5, but all other ways are still out of my reach. The same would be applied to Back button.
Hi ppl, Thanks for all who replied at least. I have talked to my seniors regarding this and they have now understood and have compromised with the browser menu buttons. So now my task has become easy. Now, I am using a variable and making it true by default. As, I mentioned earlier I just have to catch the onbeforeunload and popup a message when user tries to leave. The message will not popup when user is navigating to other pages, as I have made the variable as false on all the links of my page using following piece of code:
document.onclick = function() {
//To check if user is navigating from the page by clicking on a hyperlink.
if (event.srcElement.tagName == 'A')
blnShowMsg = false; //To not popup the warning message
else
blnShowMsg = true; //To popup the warning message
}
In my case still the message is shown when user does Refresh, back or goes to any link in Favorites, etc.
Thanks buddy, but I have already gone through that and didn't find much help there too. My seniors are not happy with that solution as putting a flag on every link of my application is a complicated job and they fear of breaking the application. Any other suggestions would be appreciated. Thanks once again.
Is there no one who can think of a solution here!!! where are all the experts???
The question isn't an unusual one. Yet after 5 days searching the internet you still haven't found a satisfactory answer. That in itself should be a fairly plain indicator.
What I've found on the web is there is a serious aversion to the 'no can do' answer. When something can't be done the normal response is to make no response.
Bottom line is not only can what you are trying do not be done it should not be done.
I think you need to go back to your seniors and explain to them that a Web UI is a guest hosted by a browser on a client machine. This guest status is an important one.
Would you want a guest in your home to have the power to enforce you to alert them when you want to go to the toilet? No?
Similarly the browser limits what info the guest UI is allowed to access. Even if you found a workaround for the fact that browsers aren't giving up this info voluntarily, such clever hacks are fragile and likely to be constant source of bugs.
Since its likely that the application was originally intended to be delivered via the browser before any code was cut, the fault lies with including the requirement in the first place.
All we can do sympathise with you in being asked to perform an near impossible and certainly not sensible requirement.
Add this script to your HTML:
window.onbeforeunload = function (e)
{
e = e || window.event;
var y = e.pageY || e.clientY;
if (y < 0){
return "Do You really Want to Close the window ?"
}
else {
return "Refreshing this page can result in data loss.";
}
}
In your function:
document.onclick = function()
{
//To check if user is navigating from the page by clicking on a hyperlink.
if (event.srcElement.tagName == 'A')
blnShowMsg = false; //To not popup the warning message
else
blnShowMsg = true; //To popup the warning message
}
blnShowMsg will be true for any click on your page except sometimes when the user click a link. I say sometimes because if event.srcElement.tagName doesn't work in some browser it will allways be true. And you have to add lots of cases to to allow using form controls etc... Some browsers can even automatically reload a page, and I'm not sure if onload events will run then or not.
But popping a warning about leaving the page (or similar) all the time is sure to annoy a lot of people, and they'll probably leave permanently...
If you're making for instance a online program where it's critical that something is saved before leaving, I'll say that catching the before unload event is a little too late, better to make some kind of autosave (see Gmail) and/or some kind of non-obtrusive warning when the user mouseover the navigation menues without saving.
But you can't force stupid users not to do anything stupid, on a web interface this is even more true because you have less controll: if the user want to terminate the program before saving they will find a way to do so, and they will call you and complain when the unsaved data dissapears ;P
I have a method that is a bit clunky but it will work in most instances.
Create a "Holding" popup page containing a FRAMESET with one, 100% single FRAME and place the normal onUnload and onbeforeUnload event handlers in the HEAD.
<html>
<head>
<script language="Javascript" type="text/javascript">
window.onbeforeunload = exitCheck;
window.onunload = onCloseDoSomething;
function onCloseDoSomething()
{
alert("This is executed at unload");
}
function exitCheck(evt)
{
return "Any string here."}
</script>
</head>
<frameset rows="100%">
<FRAME name="main" src="http://www.yourDomain.com/yourActualPage.aspx">
</frameset>
<body>
</body>
</html>
Using this method you are free to use the actual page you want to see, post back and click hyperlinks without the outer frame onUnload or onbeforeUnload event being fired.
If the outer frame is refreshed or actually closed the events will fire.
Like i said, not full-proof but will get round the firing of the event on every postback.
I believe there was some ways to do this in some browsers (and probably not very reliably) some years ago. Because I remember those awful massive spam-popups that spawned more popups as you closed one. But that's why it's not a good idea to allow scripts to detect this, and why browsers should prevent it and most modern browsers probably does.
I was asked to do something similar for a survey invitation script; they wanted to ask the visitor if they would like to answer a survey about their website, and then the survey should pop up when they leave the site. The solution I found was to (repeatedly) explain the management that this was probably impossible, or at best very unreliable; and instead the survey should popup immediately (if the visitor agreed to take the survey) and the intro page should tell the visitor to leave this window open and go back to it after reviewing the page.
onunload and onbeforeunload are not meant for this, so will naturally be unreliable.
A better solution is to change the problem. Have the client send a heartbeat, periodically telling the server the page is still active. When the hearbeat stops, you know you can clean up the server.
You might find this interesting: https://stackoverflow.com/a/3586772/1483977
Or this: Identifying Between Refresh And Close Browser Actions
"Thanks buddy, but I have already gone through that and didn't find much help there
too. My seniors are not happy with that solution as putting a flag on evry link of my
application is a complicated job and they fear of breaking the application. Any other
suggestions would be appreciated. Thanks once again."
If you use jQuery, you can add link flags automatically. The way I would handle your problem is when the user performs the "dangerous" actions, iterate all the page links that are "dangerous" and then bind events to them.
$("#dangerbutton").click(function(){
$("a").not( safeList ).click(function()
{
var dest = $(this).attr('href');
someWarningFunction(function(){
/* Stay where we are because user opted to stay */
},function(){
/* Continue Following Link because user didn't mind */
window.location= dest;
});
return false;
});
});
This way will only fire on link clicks on your page. Users have to get used to the fact that "close window == cancel everything" logic, because many use and trust that facility.
You might have seen in many of the web form pages to warn the user before closing the page.When somebody refreshes the page, then there is a chance for loosing all filled data. In that case it is very helpful.
Page life cycle includes two events like onunload and onbeforeunload. For this case you need to bind the script function in window. Onbeforeunload so that it will be called when page is unloading.
Again this warning should not be fired when you are actually submitting the page. For that set a boolean value (e.g. shouldsubmit) to submit the page.