Displaying a custom dialog when the user exits the browser? - javascript

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

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.

jQuery beforeunload custom pop up window for leaving a page

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

Is there any way to handle the browser/tab close other than beforeunload or onbeforeunload or unload

Is there any way to handle the browser/tab close other than beforeunload or onbeforeunload or unload. because I tried all the 3 events but the default pop up is coming. I don't want that default pop up but I want do something on the close click.
You can't outright block the closure of a window/tab with preventDefault or any other method. Because of this limitation, you can't use a custom modal, etc. to show a message. Your only option is to return a message, which can be bypassed.
window.onbeforeunload = function(){
return "Do you want to leave?";
}
(Demo: http://jsfiddle.net/9sAE4/embedded/result/)
Note that Firefox does not presently show the user the included message, but rather a generic message asking if the user wishes to leave.
No. The only way to do anything when the window is closed is to use onbeforeunload, and the things you're allowed to do are quite limited. Firefox and Chrome prevent your using alert or confirm, for instance (but do support returning a string from the handler, which then they'll use to show the user the choice to stay on the page). Some browsers may allow synchronous ajax calls, but I don't think all do, and I'd avoid it if I were you. You can probably set items in local storage.
From your comment:
I dont want to close the browser/tab and I want to show my own Pop up
You can't. All you can do is hook onbeforeunload and return a string, which the browser will use to offer the user a chance to stay on the page. You can't style that window, or control it.
window.onbeforeunload = function() {
return "Your message here.";
};
Example
Note that recent versions of Firefox don't even show your message, they just use a generic "This page is asking you to confirm that you want to leave - data you have entered may not be saved." (or similar) instead.

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.

Javascript close alert box

I want to be able to close an alert box automatically using Javascript after a certain amount of time or on a specific event (i.e. onkeypress). From my research, it doesn't look like that's possible with the built-in alert() function. Is there a way to override it and have control over the dialog box that it opens?
Also, I don't want an override that shows a hidden div as the alert. I need an actual dialog box.
As mentioned previously you really can't do this. You can do a modal dialog inside the window using a UI framework, or you can have a popup window, with a script that auto-closes after a timeout... each has a negative aspect. The modal window inside the browser won't create any notification if the window is minimized, and a programmatic (timer based) popup is likely to be blocked by modern browsers, and popup blockers.
Appears you can somewhat accomplish something similar with the Notification API. You can't control how long it stays visible (probably an OS preference of some kind--unless you specify requireInteraction true, then it stays up forever or until dismissed or until you close it), and it requires the user to click "allow notifications" (unfortunately) first, but here it is:
If you want it to close after 1s (all OS's leave it open 1s at least):
var notification = new Notification("Hi there!", {body: "some text"});
setTimeout(function() {notification.close()}, 1000);
If you wanted to show it longer than the "default" you could bind to the onclose callback and show another repeat notification I suppose, to replace it.
Ref: inspired by this answer, though that answer doesn't work in modern Chrome anymore, but the Notification API does.
no control over the dialog box, if you had control over the dialog box you could write obtrusive javascript code. (Its is not a good idea to use alert for anything except debugging)
I want to be able to close an alert
box automatically using javascript
after a certain amount of time or on a
specific event (i.e. onkeypress)
A sidenote: if you have an Alert("data"), you won't be able to keep code running in background (AFAIK)... . the dialog box is a modal window, so you can't lose focus too. So you won't have any keypress or timer running...
Try boot box plugin.
var alert = bootbox.alert('Massage')
alert.show();
setTimeout(function(){alert.modal('hide'); }, 4000);
I guess you could open a popup window and call that a dialog box. I'm unsure of the details, but I'm pretty sure you can close a window programmatically that you opened from javascript. Would this suffice?
The only real alternative here is to use some sort of custom widget with a modal option. Have a look at jQuery UI for an example of a dialog with these features. Similar things exist in just about every JS framework you can mention.
If you do it programmatically in JS it will be like reinventing the wheel. I recommend using a jQuery plugin called jGrowl
You actually can do this you can basically listen for this pop up to happen and then confirm true before it ever "pops up",
if(window.alert){
return true
}
You can use label and set its fade in and out time for e.g
Hide it initially and show on click.
$('#div_Message').fadeIn(500).delay(1000).fadeOut(1500);
window.setTimeout('alert("Message goes here");window.close();', 5000);

Categories

Resources