jQuery beforeunload custom pop up window for leaving a page - javascript

Hi I would like to customize my pop up for leaving a page, is there any simple way to do that?
I am using simple jQuery
$(document).ready(function() {
var myPopUp = $('#pop-up').css('display', 'block');
$(window).bind('beforeunload', function(){
return 'load my pop up here instead of the default browser message';
});
});
my html for the pop up is which is hidden by default
<div id="pop-up">
<h2>Are you sure wanna leave</h2>
Leave
Stay
</div>
Thanks

Short answer: You can't.
Longer answer:
For rather obvious "security" reasons it is very limited what you can do when a user tries to navigate away from a page / close a tab or in any other way leave the site.
The reason is that browsers want to make absolutely sure that you cannot prevent the user from closing a tab or window that he / she wants to close.
Therefore the onbeforeunload javascript event - and by extension the beforeunload jQuery event - are extremely limited in what they can do. One of the things they definitely cannot do is prevent the page from closing - except using one very standardized and rather boring method the browser (usually) allows.
Some browsers allow you to specify a message, while others (including firefox) do not even allow you to change the message (because you might trick the user by asking "Can I adopt your unborn son?")... AFAIK most browsers allow you to specify a string of your choosing in addition to a standard message that cannot be changed. Some browsers (no major desktop browsers) even lack the event completely.
What you want to achieve is basically to force the user to stay on your page, and then show a nice pop-up asking them to confirm... and while this could definitely improve the user experience in a lot of cases, you don't have to think very hard to imagine how it could be abused to simply not allow the user to ever leave.
Think about how annoying sites that break the back-button are, then imagine they could even remove your ability to close a tab!
I stumbled on this rather amusing forum question from a user who has spent an extensive amount of time trying to prevent even what little annoyance can be added - a short excerpt:
I do not like onunload and onbeforeunload. I do not think they should
EVER be fired on my firefox installation. I do not think there is any
useful application of these events, not even the benevloent "you have
unsaved work!" popups. When I tell my web browser to close a web page,
I do not want a web page to prevent (or delay) the browser from
closing it--at all ever.
And just to add a little bit of somewhat official information:
mozilla.org: WindowEventHandlers.onbeforeunload:
Since 25 May 2011, the HTML5 specification states that calls to
window.alert(), window.confirm(), and window.prompt() methods may be
ignored during this event. See the HTML5 specification for more
details.

This question have been asked and answered in several stackoverflow posts such as this one
If you can also elaborate on what the circumstances of leaving the "page", you could probably get a better and proper answer.
If you want to warn that user should save before then checkout the top post of the link. If you just want to warn before you leave the page,
try this answer that user Hunter left:
<script type='text/javascript'>
function goodbye(e) {
if(!e) e = window.event;
//e.cancelBubble is supported by IE - this will kill the bubbling process.
e.cancelBubble = true;
e.returnValue = 'You sure you want to leave?'; //This is displayed on the dialog
//e.stopPropagation works in Firefox.
if (e.stopPropagation) {
e.stopPropagation();
e.preventDefault();
}
}
window.onbeforeunload=goodbye;
</script>

https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload#Browser_compatibility
its is not possible to have a custom popup see the link specified

Related

How to read Chrome/Firefox Pop up actions Leave/Stay when we the leave the page?

When ever u made some change to page and try to leave chrome/firefox throws a alert. Data you entered may not be saved with (Leave or Stay) buttons.
How i can do certain action when user clicks leaves or stay.
To which event i need to listen to to make actions when we click leave or stay?
TIA
There is no window close event.You can use onbeforeunload to prevent asking for simple confirmation etc.
That is what is done internally by website developers on their page. But you can't read that answer from an user script. It is simply the website developers implementation.You can't read user's response given to website developers confirm question by user from an application.
Those popups are implemented by the corresponding websites not browser.
Solution
Modern browsers now consider displaying a custom message to be a security hazard and it is removed therefore. Browsers now only display generic messages. So we can simply do this:-
window.onbeforeunload = function() {
return false;
};
window.onbeforeunload = null; // this will not show any popup.
So just remove everything fron onbeforeunload and return false and make it null. This will solve your problem.
Note: You can't show custom message or do anything significant using onbeforeunload. That is the answer to your question originally asked.

Why trigger F11 press event doesn't work?

I just read this question: Full Screen Page by pressing button instead of F11
The op asked to replace F11 with other hot keys, so I'm wondering that maybe I can simulate press F11 to get things work.
I learned that I can use trigger in JQuery to simulate key press event, so I do something like this:
$("body").keyup(function (e) {
alert(e.which);
});
var e = $.Event("keyup");
e.which = 122; // # Key code of F11
$("body").trigger(e);
When I run this, I got the alert says 122, but it seems that it doesn't give the hoped result. Is there a restriction there?
I made a fiddle here: http://jsfiddle.net/ap295/5/
I think this is the one :) to detect it ...
$(document).keyup(function(e){
if(e.which==122){
e.preventDefault();//kill anything that browser may have assigned to it by default
//do what ever you wish here :)
alert('F11 pressed');
return false;
}
});
but triggering it (NOT POSSIBLE)
But you will not prevent the browser from full screen :) ...
Reson given is that , lets say I have full screened it somehow, and wish to toggle out of it using F11 but u are preventing me, I would have to restart PC, [computer illiterates] which poses security risk as you are preventing a user from doing something he is expecting to do, and they may think PC is broken or something :) so ...there you are.
You can not do this. The linked answer in that question provides a way with jQuery to simulate key-presses, within the jQuery event framework.
You simply can not trigger or fake keypresses. So the answer of this question is:
No, this is impossible
You won't be able to override the browser's built-in hotkeys from within a web page.
You might be able to do it in a browser extension, but that's would surely be serious overkill just to change the application's hotkeys.
In any case, why would you even want to override the standard keyboard shortcuts? I don't get that. They've been standard for a long time; most users will be familiar with them, and will find it very odd if they've been changed to something else.
Don't look at is as a question of "How do I trigger F11?" - look at is as "How do I trigger or simulate full-screen?"
With older versions of IE you can open a new window straight into full-screen:
window.open(someURLorOther, '', 'fullscreen=yes, scrollbars=auto');
Or you can use window.open to open a new window of a specific size.
Or you can try to resize the current window to fill the screen:
moveTo(0,0);
resizeTo(screen.availWidth,screen.availHeight);
However just because you can doesn't mean you should. You should never resize the current window - this annoys practically everyone. Opening a new window to a size you choose is more reasonable, though if it's too big it can be annoying, and on a normal web page (where by "normal" I probably mean not some kind of browser-based data-entry app) it is nicer not to open new windows.

Displaying a custom dialog when the user exits the browser?

Yes, I realize this is horrible UI and bad accessibility wise, but I am forced to seek out the options due to contracted work ( to which I didn't initially agree upon and am stuck with ).
I know that you can assign an event handler to onbeforeunload like:
window.onbeforeunload = function() {
return 'You have unsaved changes!';
}
That would bring about a dialog generated by the OS/browser which cannot be customized. It would ask you to Cancel your request or go on.
So far it seems the only way I can display any custom-ness is by inserting a window.open in that event handler:
window.onbeforeunload = function() {
var x = window.open('modal.html');
}
This would most likely get blocked by any modern browser as a "popup". I have to display an entirely new page with my dialog, but this seems to be the only way to meet the demand.
Is this pretty much the only option I have? Other than forcefully telling the client it isn't recommended to do this?
The only other option would be relying on the user to hit "Cancel request" and then insert the dialog.
Questions I have already looked at:
jQuery UI Dialog OnBeforeUnload
How can I override the OnBeforeUnload dialog and replace it with my own?
As per the questions you already looked at, you cannot customize that dialog beyond passing in a string message to be displayed by the browser.
window.onbeforeunload - MDC
I just went the window.open route onbeforeunload.
you could use a hidden Flash .swf that you reveal at onbeforeunload time instead of window.open

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.

To detect if the user is closing the IE browser apart from onunload event, as it is triggerred when user does refresh etc [duplicate]

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.

Categories

Resources