How to block users from closing a window in Javascript? - 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.

Related

Stop user from X'ing out of modeless window without alert

I have a client that is using JSP (Java) and Javascript/JQuery for their pages. I have a requirement for a particular modeless pop up page that states the user cannot X out of the window if there is text in the description textarea (they will need to use a cancel button or clear out the text). That's part is easy and I have found a ton of ways to do it online. The part I am having trouble with is: They do NOT want the error in an alert box, they want the error message simply displayed in the same window without having to click and close the alert. I cannot seem to find anything that will disable the X button without the alert box. Also, we're browser agnostic, so the solution must work for any browser.
If this alert is enforced by the browser and there's no way around it, I can obviously explain that to the client, but I am not sure if that's the case or not.
So, I am asking ether for some ideas on how to meet the requirement or if the requirement is impossible, some evidence to back that up.
This is what I've tried so far but gives the alert box, so it does not satisfactorily meet the requirement:
function isDescriptionPopulated() {
var desc = $("#description")
.val();
if (desc === "") {
return false;
} else {
return true;
}
}
window.addEventListener('beforeunload', function(e) {
if (isDescriptionPopulated()) {
e.preventDefault();
e.returnValue = undefined;
}
});
I am far from a Javascript expert, so I'm hoping maybe one of you can guide me in the right direction.

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.

Implement a Back-Button 'Warning' in Javascript for use in Flex

I have a Flex application where I want to give the user a warning if they hit the back-button so they don't mistakenly leave the app. I know this can't be done entirely in Actionscript due to cross-browser incompatibility. What I'm looking for is just the Javascript implementation to catch the back-button.
Does anyone have a simple non-library cross-browser script to catch the back-button? I can't seem to find a post that shows an example.
You can use the window.onbeforeunload event.
window.onbeforeunload = function () {
return "Are you sure you want to leave my glorious Flex app?"
}
The user can press okay to leave, cancel to stay.
As you stated, this throws the alert any time the page changes. In order to make sure it only happens on a back button click, we have to eliminate the alert message whenever they're leaving the page from natural, expected sources.
var okayToLeave = false;
window.onbeforeunload = function () {
if (!okayToLeave) {
return "Are you sure you want to leave my glorious Flex app?"
}
}
function OkayToLeave() {
okayToLeave = true;
}
You'll have the responsibility of setting the variable to true whenever they click a button or link that will take them from that page naturally. I'd use a function for unobtrusive javascript.
Set your event handlers in the DOM ready:
referenceToElement.addEventListener('onClick', OkayToLeave(), false);
This is untested, but should point you in the right direction. Although it may seem like a nuisance to do this, I imagine it's more complete functionality. It covers the cases where a user may click on a favorite, or be redirected from an external application.

Display a warning when leaving the site, not just the page

This sounded like something almost impossible to do when it was presented to me. I know you can display a dialog box to confirm when leaving a web page. But is it possible to display a dialog box when leaving a site?
I haven't been able to find/create anything that can read the address bar and know that you're leaving the site.
First off define which events can actually take your user away from your site?
A click of a link inside your web site content
A submit of a form to an outside action
A javascript from a child window that changes window.location on its parent
User starting a search in the search bar (FF and IE)
User entering a search/address in the browser address bar.
User hitting a back button (or backspace) when it just came to your site
User hitting a forward button (or shift-backspace) when they were off the site before but came back by getting there via Back button functionality
User closes the browser window
So. what can you do about all these?
These are easy. Check your anchors and if they do point outside, add some functionality in the onclick event
Similar to 1. Add your functionality for the onsubmit event of the form posting back outside of your site.
-> 8. don't really have an applicable solution that could be controlled. You can abuse onbeforeunload event as much as you want, but you won't have much success of knowing what's going on. And there are certain limitations related to onbeforeunload as well, so your hands will be tied most of the time.
The real question?
Why would you want to control this event anyway except for bothering your users not to leave you. Begging doesn't give much justice in the web world anyway. And when some site would bother me with messages or even worse prevent me from leaving I wouldn't want to get back anymore. It smells of bad bad bad usability and gives a hint of adware site.
Rather try to keep your users interested by providing them with valuable content.
Your best bet is listening on the non-standard beforeunload event. This is supported by almost all browsers, expect of Opera which is known to adhere the W3C standards extremely strictly.
Kickoff example:
window.onbeforeunload = function() {
return "You're leaving the site.";
};
This message will show up in kind of a confirmation dialogue.
In your specific case you need to turn it off (just set to null) whenever a navigational link is clicked or an internal form is submitted. You can do that by listening on the click event of the desired links and the submit event of the desired forms. jQuery may be of great help here:
window.onbeforeunload = function() {
return "You're leaving the site.";
};
$(document).ready(function() {
$('a[rel!=ext]').click(function() { window.onbeforeunload = null; });
$('form').submit(function() { window.onbeforeunload = null; });
});
You only need to give all external links the defacto standard attribute rel="ext" to denote that those are external links.
Google
This may help
You need to check onclick event before attach initLocalLinkException();
Disclaimer: It's not tested.
HTML:
internal link
html anchor
external link
blank external link
<form action="test.html" method="post" >
<button type="submit">Post Button</button>
</form>
JavaScript:
$(document).ready(function () {
initLocalLinkException();
window.onbeforeunload = function () { confirmExit() };
$('form').submit(function () {
window.onbeforeunload = null;
});
});
function initLocalLinkException() {
$('a').click(function () {
if ($(this).attr('target') != '_blank') {
var link = $(this).attr('href');
if (link.substr(0, 4) == 'http') {
var LocalDomains = new Array('http://www.yourdomain.com',
'https://yourdomain.com',
'localhost', '127.0.0.1');
var matchCount = 0;
$.each(LocalDomains, function () {
if (this == link.substr(0, this.length)) {
matchCount++;
}
});
if (matchCount == '0') {
confirmExit();
} else {
window.onbeforeunload = null;
}
} else { window.onbeforeunload = null; }
}
});
}
function confirmExit() {
alert('Are you sure?'); // Do whatever u want.
}
Take a look at this thread.
One possible way to achieve this would be to use Javascript to examine all of the a tags on your page when it loads and check if they are linking to an external site. If so, you can add an onclick event to show a confirm/alert box or something more elegant. Of course, using jQuery will greatly simplify the Javascript you'll have to write, like in the above thread.
Using the expression from this question, you can do the following:
$.expr[':'].external = function(obj){
return !obj.href.match(/^mailto\:/) && (obj.hostname != location.hostname);
};
$.expr[':'].internal = function(obj){
return obj.hostname == location.hostname;
};
$(function() {
var unloadMessage = function() {
return "Don't leave me!";
};
$('a:internal').click(function() {
window.onbeforeunload = null;
});
$('form').submit(function() {
window.onbeforeunload = null;
});
$('a:external').click(function() {
window.onbeforeunload = unloadMessage;
});
window.onbeforeunload = unloadMessage;
});
It's possible. Just try entering a question or answer to SO and then navigating away before submitting it. It doesn't matter whether you click on a link or type in the address bar, you get an "Are you sure?" alert. You might post over on SO Meta asking how they do this.
You can do that if you design your site as a one page web app.
It means, a single page is loaded, then other contents are loaded dynamically using ajax.
In that case the onbeforeunload is triggered when the user leave the page/site.

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.

Categories