prevent onbeforeunload to close page in any case - javascript

I want to prevent browser to close page in any case or in other case, Prevent browser to do anything when onbeforeunload is called.
Here is my code which i have tried.
(function() {
var proxied = window.onbeforeunload;
window.onbeforeunload = function(e) {
e.preventDefault();
e.stopPropagation();
//i want to stop everything
console.log('stay here');
// return 'message';
};
})();
I want to perform a action before leaving the page (disconnect the
chat)

You can't outright prevent a user from leaving the page (This would lead to much abuse on spam/advertisement sites who try to get you to stay on a page), but you can show things such as a window which causes a confirm prompt to the user. Have a look at Prevent a webpage from navigating away using JavaScript which can lead you to the right direction of what you're trying to accomplish.

There is no way to stop browser to close. The browser doesn't allow you to do that.

Related

How to disable browser feature

I am developing a project where user gets a conformation page. I want user not to click back or close tab or reload.
Now either I need to disable the browser features or get back button,tab close event, or reload event to java script so that I could take the needed steps to prevent my data to get lost.
I have used this:
window.onbeforeunload = function()
{
return "Try This";
};
But this get called even when I click a button that redirects the page.
If you just want to have the alert, understanding that the user is ultimately in control and can bypass your alert, then do what you're doing but use a flag that disables it when you're navigating and don't want the alert. E.g.:
var warnWhenLeaving = true;
window.onbeforeunload = function() {
if (warnWhenLeaving) {
return "your message here";
}
};
then in a click handler on the link/button/whatever that moves the user on that you don't want this to pop up on:
warnWhenLeaving = false;
In a comment you asked:
can i know that what user has clicked when alert is generated with this function. That is can i know what user has clicked (leave this page/stay on page)
The answer is: Sort of, but not really; you're almost certainly better off not trying to.
But: If you see your onbeforeunload function run, then you know the user is leaving the page and the browser is likely to show them your message. The browsers I'm familiar with handle the popup like an alert: All JavaScript code on the page is blocked while the popup is there. So if you schedule a callback via setTimeout, you won't get the callback if they leave and you will if they stay:
window.onbeforeunload = function() {
if (warnWhenLeaving) {
setTimeout(function() {
display("You stayed, yay!");
}, 0);
return "No, don't go!";
}
};
Live Example
So in theory, if you get the callback, they stayed; if you see an unload event, they left. (Note that there are very few things you can do in an unload event.)
I've tried that on current Chrome, current Firefox, IE8, and IE11: It works on all of those. Whether it will work in the next release of any of them is anybody's guess. Whether it works reliably on mobile browsers is something you'd have to test, and again could change.

Detect/Warn when back button is pressed

Is there a way detect/catch the browser back button being pressed and in doing so ask them if they are sure about going back?
Building an application and it will soon be converted to an ajax based application and per requirements it's supposed to reset the application if a user goes 'back'...
I mainly want this to catch the accidental back button presses as I personally feel that if someone can't follow the directions that are given to them at the beginning of the application.... I'm not worried about their extra work.
If there isn't a way to do this is would the best solution be to launch the application in a new window/tab so that there is no history for it to go back to?
you can use onbeforeunload to detect back button or accidental page navigations:
window.addEventListener("beforeunload", function() {
var ans = confirm("Are you sure?");
if (ans) {
//TODO: add your code here
}
}, false);
to replace the current page in browser history you can use window.location.replace():
window.location.replace("yourNewURL");
You can also set the onbeforeunload function like this:
window.onbeforeunload = function() {
return "Are you sure you wish to leave?";
};

How to block users from closing a window in Javascript?

Is it possible to block users from closing the window using the exit button [X]? I am actually providing a close button in the page for the users to close the window.Basically what I'm trying to do is to force the users to fill the form and submit it. I don't want them to close the window till they have submitted it.
I really appreciate your comments, I'm not thinking of hosting on any commercial website. Its an internal thing, we are actually getting all the staff to participate in this survey we have designed....
I know its not the right way but I was wondering if there was a solution to the problem we have got here...
Take a look at onBeforeUnload.
It wont force someone to stay but it will prompt them asking them whether they really want to leave, which is probably the best cross browser solution you can manage. (Similar to this site if you attempt to leave mid-answer.)
<script language="JavaScript">
window.onbeforeunload = confirmExit;
function confirmExit() {
return "You have attempted to leave this page. Are you sure?";
}
</script>
Edit: Most browsers no longer allow a custom message for onbeforeunload.
See this bug report from the 18th of February, 2016.
onbeforeunload dialogs are used for two things on the Modern Web:
Preventing users from inadvertently losing data.
Scamming users.
In an attempt to restrict their use for the latter while not stopping the former, we are going to not display the string provided by the webpage. Instead, we are going to use a generic string.
Firefox already does this[...]
If you don't want to display popup for all event you can add conditions like
window.onbeforeunload = confirmExit;
function confirmExit() {
if (isAnyTaskInProgress) {
return "Some task is in progress. Are you sure, you want to close?";
}
}
This works fine for me
What will you do when a user hits ALT + F4 or closes it from Task Manager
Why don't you keep track if they did not complete it in a cookie or the DB and when they visit next time just bring the same screen back...:BTW..you haven't finished filling this form out..."
Of course if you were around before the dotcom bust you would remember porn storms, where if you closed 1 window 15 others would open..so yes there is code that will detect a window closing but if you hit ALT + F4 twice it will close the child and the parent (if it was a popup)
This will pop a dialog asking the user if he really wants to close or stay, with a message.
var message = "You have not filled out the form.";
window.onbeforeunload = function(event) {
var e = e || window.event;
if (e) {
e.returnValue = message;
}
return message;
};
You can then unset it before the form gets submitted or something else with
window.onbeforeunload = null;
Keep in mind that this is extremely annoying. If you are trying to force your users to fill out a form that they don't want to fill out, then you will fail: they will find a way to close the window and never come back to your mean website.
How about that?
function internalHandler(e) {
e.preventDefault(); // required in some browsers
e.returnValue = ""; // required in some browsers
return "Custom message to show to the user"; // only works in old browsers
}
if (window.addEventListener) {
window.addEventListener('beforeunload', internalHandler, true);
} else if (window.attachEvent) {
window.attachEvent('onbeforeunload', internalHandler);
}
If your sending out an internal survey that requires 100% participation from your company's employees, then a better route would be to just have the form keep track of the responders ID/Username/email etc. Every few days or so just send a nice little email reminder to those in your organization to complete the survey...you could probably even automate this.
It's poor practice to force the user to do something they don't necessarily want to do. You can't ever really prevent them from closing the browser.
You can achieve a similar effect, though, by making a div on your current web page to layer over top the rest of your controls so your form is the only thing accessible.
Well you can use the window.onclose event and return false in the event handler.
function closedWin() {
confirm("close ?");
return false; /* which will not allow to close the window */
}
if(window.addEventListener) {
window.addEventListener("close", closedWin, false);
}
window.onclose = closedWin;
Code was taken from this site.
In the other hand, if they force the closing (by using task manager or something in those lines) you cannot do anything about it.

Ask whether the user is sure to leave the site (XHTML/JavaScript)

When a user leaves one page of my website, there should be a warning message which gives the user the option to stay on the page:
"Are you sure that you want to close this page?"
It doesn't matter if the next page is an internal or external page.
I thought this could be done with the onUnload event handler, couldn't it?
<body onunload="confirmClose()">
The confirmClose() function must then show a message box with two buttons so that the user can choose between "Really leave" or "Stay".
function confirmClose() {
return confirm('Really leave this page?')
}
But this function can't stop the unload, right?
Do you have a solution for my problem? Thanks in advance!
You can only provide the text. The browser handles the dialog box (security reasons). Here is some code you can use:
window.onbeforeunload = function (e) {
var e = e || window.event;
var msg = 'Are you sure you want to leave?';
// For IE and Firefox
if (e) {
e.returnValue = msg;
}
// For Safari / chrome
return msg;
}
Try this out on different browsers, though. You'll notice the message should be constructed differently depending on the different browsers' dialog wording.
Here is what I use:
if (IsChrome) {
return 'You were in the middle of editing. You will lose your changes if you leave this page';
} else {
return 'You were in the middle of editing. Press OK to leave this page (you will lose your changes).';
}
You can add an onbeforeunload event. Note that it can only return a text string to include in the dialog the browser will display when the event is called. You can't tweak the dialog beyond that, nor can you trigger your own confirm as you're trying to do.
I'd note that this is very, very annoying behaviour except in a few specific situations. Unless you're saving me from significant data loss with this, please don't do it.
The browser takes care of displaying the confirm window.
You need to return the string with the message that you want to ask. Also, you may want to use onbeforeunload for cross browser compatibility.

Alerts when navigating away from a web page

When I try to close my Google docs tab with unsaved changes, this is what I get in my browser (FF 3.5).
Are you sure you want to navigate away
from this page?
You have unsaved changes in this
document. Click Cancel now, then
'Save' to save them. Click OK now to
discard them.
Press OK to continue, or Cancel to
stay on the current page.
My question is whether such alerts are part of the web app (gdocs for eg.) or are they given out by the browser? If latter, how is this done?
By the browser. It's the beforeunload event handler that returns the customized text of the dialog, which is only the middle of the three paragraphs - the other two paragraphs as well as the text of the buttons cannot be customized or otherwise changed.
window.onbeforeunload = function(){ return 'Testing...' }
// OR
var unloadListener = function(){ return 'Testing...' };
window.addEventListener('beforeunload', unloadListener);
Will yield a dialog that says
Are you sure you want to navigate away from this page?
Testing...
Press OK to continue, or Cancel to stay on the current page.
You can nullify this by setting the handler to null
window.onbeforeunload = null;
// OR
window.removeEventListener('beforeunload', unloadListener);
The alerts are part of the web application. View the source code and look at the javascript.

Categories