Prevent browser from closing in asp.net - javascript

I am using asp.net 2.0 with c#.
i want a pop up to be displayed when user tries to close the browser and if user click on "no" [i.e. he don't want browser to be closed] then it prevent browser to get closed.
Please help.
Thanks

the code they use is
window.onbeforeunload=function() {
if (somereasonorother) return "You did not save your stuff"
}

Pointy, this is entirely possible, and it's done by many web pages for perfectly reasonable reasons.
Try something like this:
function areYouSure() {
return "Are you sure you want to leave this page?";
}
window.onbeforeunload = areYouSure;

You can try to attach yourself to the onbeforeunload event:
<body onbeforeunload="ConfirmClose();">
But I have to mention that it won't work on all browsers. The only ones that prompted something after I closed a window were Chrome, Firefox and Internet Explorer; Opera ignored the code in the JavaScript method.
This is mostly because some browsers trigger the onbeforeunload event only when you're trying to leave the current page by visiting another one, and not when you close the current window / tab.

Related

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.

The best way to implement window close event

Long story is short - I am trying to submit a certain form when user closes the window, or is not responding for 20min.
The second I've done using this code:
timeOut = setTimeout(function () {
submitThisForm(document.forms.sendDealerInfo);
console.log("Timed out...");
}, 600000);
For the first one I've tried with this code:
window.onbeforeunload = function() {
submitThisForm(document.forms.sendDealerInfo);
clearTimeout(timeOut);
return null;
}
Unfortunately window.onbeforeunload event won't trigger in all browsers (in Chrome and Opera for example).
I also tried: $(window).unload(function () {... and window.addEventListener("beforeunload", function (event) {...
But same story - they won't work in all browsers.
Is there a way to accomplish what I am trying to do some other way? Perhaps with sessions?
As Suman says, onBeforeUnload is supported in all the major browsers. But most, if not all, the browsers will not let you do anything within that event beyond returning a string for the "Are you sure you want to leave this page?" dialog.
Then with onUnload you're attempting to submit a form after the page has already been unloaded, and navigation is already happening. It would be a very odd user experience to be navigating away then be redirected somewhere else.
Trying to submit a form when the window is closed isn't a very safe method. The web browser could crash, the user could force close it, the internet connection could be interrupted, among other things. I think your best bet would be to submit the form every so often. Possibly detecting an idle timeout of a few seconds, then submitting your form?
window.onbeforeunload is works in all major browsers, Like it is supported from Chrome 1 and Opera 12
Browser Compability

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

How to pop up an alert box when the browser's refresh button is clicked?

If the user refreshes the page in question it will add another record to the database, so I want to warn the user through an alert box if they really want to refresh the page and if they click ok then the page should be refreshed otherwise if they click cancel it won't be.
How to make this type of alert box appear when the browser's refresh button is clicked in a way that is cross browser compatible?
You can do it like this:
window.onbeforeunload = function() {
return "Data will be lost if you leave the page, are you sure?";
};
This would show a prompt to the user allowing them to cancel. It's not refresh specific, but for your purposes (like editing a question on SO) that doesn't seem to matter, it's loss of info no matter where you're leaving to.
There isn't a way to tie it to just the refresh action, but you may want to look into window.onbeforeunload. This will allow you to run a function that returns a string just before the page is unloaded. If this string is not empty, then a popup confirmation dialog, containing this string and some other boilerplate text provided from the browser.
For example:
window.onbeforeunload = function () {
if (someConditionThatIndicatesIShouldConfirm) {
return "If you reload this page, your previous action will be repeated";
} else {
//Don't return anything
}
}
Also, if the current page was loaded via a POST operation, then the browser should already display a confirmation box when the user tries to refresh it. As a general rule, any action that changes the state of the data on the server should be done through a POST request, rather than a GET.
All the answers are quite old, as of today 2020, according to HTML specification, you can do it this way.
Important Note: Custom text is not supported in most of the browsers now. (it was supported in older browsers).
https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload
window.addEventListener('beforeunload', function (e) {
// Cancel the event
e.preventDefault(); // If you prevent default behavior in Mozilla Firefox prompt will always be shown
// Chrome requires returnValue to be set
e.returnValue = '';
});
There are two possible ways forward with this, both quite different.
One way would be to have an event handler bound to onbeforeunload event so that you can detect when the user is browsing away from the current page. If my memory serves me correctly however, onbeforeunload is not consistent across browsers (I don't think Opera responds to it IIRC, but have no way to currently test). Of course, this solution fails if the user turns off JavaScript.
The second and more robust way would be to implement the Post Redirect Get pattern which when used, prevents the data from being posted again when a user refreshes the page.
This is not possible. The best you can do is use the onbeforeunload event but that will fire on any event leaving the current page. It is not possible to target the refresh button specifically.
See e.g. this question on onbeforeunload
It might be better though to build a duplicate check into your database. That would catch accidental submissions using the "back" button as well.
An alternative would be using a random one-time token that gets built into the form. If two operations are attempted using the same token, you would stop it.
Quoting from official Mozilla site here, It is no longer supported to supply a custom message.
When this event returns (or sets the returnValue property to) a value other than null or undefined, the user will be prompted to confirm the page unload. In older browsers, the return value of the event is displayed in this dialog. Starting with Firefox 44, Chrome 51, Opera 38, and Safari 9.1, a generic string not under the control of the webpage will be shown instead of the returned string. For example:
Firefox displays the string, "This page is asking you to confirm that you want to leave - data you have entered may not be saved." (see bug 588292).
Chrome displays the string, "Do you want to leave this site? Changes you made may not be saved." (see Chrome Platform Status).

How to close browser in a given time?

how to close a browser window within given time using javascript also without the warning message in IE and Firefox
I agree with the other guys. without looking too hard, I'd say you're out of luck closing a window in javascript without getting a warning message.
Any javascript you write will be executed by the browser. If that browser decides to trap a window.close() piece of script, then that's what it's going to do. You're constrained by the boundaries the browser places on you.
Warining message is browser-dependent and you cant omit that. As far as I remember, you need to open window with script to have rights to close it.
You can only close a window (with no user warning) that was previously opened with a script.
You can't, the warning message is designed to stop code from disruptively closing windows.
Use setTimeout to manage when to run your window.close() script.
EDIT : For warning message, I don't know the solution.
For the warning message, I know StackOverflow uses the onbeforeunload event. If you override that event (not just attach a handler) with a function that returns false, it'll probably get rid of the warning. For example:
window.onbeforeunload = function(){return false;};
setTimeout(function(){window.close();}, 10000); // close after 10 seconds
Just as a general principle, web browser windows belong to the user, not to you. If you are looking to create, destroy, or resize them, you are doing something wrong.
Please put your RL address in your profile. We will be sending a "reeducation team" over to visit you shortly. :-)
Only works in IE:
window.setTimeout(function() {
window.opener='x';
window.close();
}, 10000);
It seems like you can do it (though you shouldn't). Check this question
Javascript to close IE6, IE7, IE8 and Firefox without confirmation box?

Categories

Resources