Window closing even on clicking 'cancel' button in confirmation box - javascript

In my website i conduct an exam in new window & i want that if a user closes this window, he will be redirected to other page if he presses 'ok' on confirmation. But he should stay there if presses 'cancel'. The javascript i'm using is below.
/**
* This javascript file checks for the brower/browser tab action.
* It is based on the file menstioned by Daniel Melo.
* Refer: http://stackoverflow.com/questions/1921941/close-kill-the-session-when-the-browser-or-tab-is-closed
*/
var validNavigation = false;
function endSession() {
$choice = confirm("You will exit your CSA test. Are you sure you want to close the window?");
if ($choice)
window.open('Result.aspx', '_blank', 'toolbar=0, scrollbars=1');
}
function wireUpEvents() {
window.onbeforeunload = function () {
if (!validNavigation) {
endSession();
}
}
// Attach the event keypress to exclude the F5 refresh
$(document).bind('keypress', function (e) {
if (e.keyCode == 116) {
validNavigation = true;
}
});
// Attach the event click for all links in the page
$("a").bind("click", function () {
validNavigation = true;
});
// Attach the event submit for all forms in the page
$("form").bind("submit", function () {
validNavigation = true;
});
// Attach the event click for all inputs in the page
$("input[type=submit]").bind("click", function () {
validNavigation = true;
});
}
$(document).ready(function () {
wireUpEvents();
});
Here on clicking 'ok' button the 'Result.aspx' window opens successfully, but the problem here is that if user clicks 'cancel' in the confirmation box then also the window is getting closed.
Please tell me where am i going wrong or any alternative to this.
Any kind of any help will be appreciated.
Thanks in advance!!

You can't actually stop the user from leaving your page. The final dialog (controlled by the browser), that asks if they want to stay on this page or leave, is up to them.
Your use of confirm() simply provides a dialog for the user, which you can get the choice from, but has no effect on the page being left. If you return a value from window.onbeforeunload, it prompts the user with that final dialog I mentioned, but you cannot capture their choice, nor can you control it.
There's nothing you can do to actually stop a user from leaving your page.

Related

How to handle browser close event through Java script

I have an application which logs users session once he logins. Say i have view case page and when user click a case it would be locked by that user and the action is tracked by inserting an entry into lock table with the java Session, caseid and userId. Now when the user click any other tab within the application, including logout an action is called to delete the session id in the lock table for that user and case. I have a requirement to release this lock even when the user closes the browser close button. My backend code will handle the scenario when the elapsedTime of the lock is greater than 10mins. However when the user closes the browser and some other user logins to view the same case within this span of 10mins it still shows the lock by the previous user. So i have to catpure the browser close event and do the same action as i do for logout and other tab click. My below piexe of java script code works well in IE browser for browser close but doesnt work in chrome or firefox. Can someone suggest which event to use in chrome/firefox please?
<script type="text/javascript">
document.getElementById('logoff').onclick = function(){
sessionStorage.setItem('accept', '0');
location.href="/abc/logout/";
};
$(document).ready(function(){
var validNavigation = false;
// Attach the event keypress to exclude the F5 refresh (includes normal refresh)
$(document).bind('keypress', function(e) {
if (e.keyCode == 116){
validNavigation = true;
}
});
// Attach the event click for all links in the page
$("a").bind("click", function() {
validNavigation = true;
});
// Attach the event submit for all forms in the page
$("form").bind("submit", function() {
validNavigation = true;
});
// Attach the event click for all inputs in the page
$("input[type=submit]").bind("click", function() {
validNavigation = true;
});
$("input[type=button]").bind("click", function() {
validNavigation = true;
});
window.onbeforeunload = function() {
if (!validNavigation) {
sessionStorage.setItem('accept', '0');
location.href="/abc/logout/";
}
};
});
</script>
It seems like using the onbeforeunload property is discouraged:
Typically, it is better to use window.addEventListener() and the beforeunload event, instead of onbeforeunload.
It should look like this:
window.addEventListener('beforeunload', function (e) {
// the absence of a returnValue property on the event will guarantee the browser unload happens
delete e['returnValue'];
if (!validNavigation) {
sessionStorage.setItem('accept', '0');
location.href="/abc/logout/";
}
});

When a user clicks the fineuploader button, how can I redirect them instead of showing the file selection dialog?

We are using .net and fineuploader. If the users session has timed out and they click the fineuploader button, we need to be able to redirect them to a login page instead of showing them the file selection dialog.
We have been able to sort-of do it in the "submit" event of fineuploader but the user still sees the file selection dialog before they do our redirect.
$("#fine-uploader").fineUploader().on("submit", function (event, id, name)
{
if (noSession){
cancelUploads();
window.onbeforeunload = function () { return; }
location.href = "/login";
}
}
I did not see any events that fire before the file selection dialog, unless I missed it (http://docs.fineuploader.com/api/events.html).
Is there a way to do something before the file selection dialog is shown?
The solution is probably as simple as attaching a click handler to the underlying file input element, preventing the browser's default action on click (which normally shows the file chooser), and then redirect the user to the page of your choice:
document.querySelector('input[type="file"]')
.addEventListener('click', function(event) {
event.preventDefault()
location.href = "/login"
})
Add this event handler when you want to redirect, and remove it when you don't. Or, you can add it after the uploader has been created, and add some logic to the click handler function that only prevents the default action and redirects if the user must re-login.
Warning: I have not tested this cross-browser (only Chrome).
you can use prevent default to stop the submit action and run your check.
Use an else statement to finish the submit if they are logged in.
$("#fine-uploader").fineUploader().on("submit", function (event, id, name)
{ event.preventDefault();
if (noSession){
cancelUploads();
window.onbeforeunload = function () { return; }
location.href = "/login";
}
else{
return true;
}
}
https://api.jquery.com/event.preventdefault/

How do I add jQuery to a submit button which fires before Paypal objects?

I have a Paypal Digital Express form which works fine. However, I would like to add a bit of jQuery to the submit button which will fire -before- the Paypal popup window opens and can prevent the Paypal code from firing. Unfortunately, the Paypal window always open first.
jQuery('#buyLink').click( function(e) {
e.preventDefault();
// if no boxes are checked; no songs selected
if ( jQuery("#buysongs input:checkbox:checked").length == 0) {
alert('Please select at least one song!');
return false;
}
});
Is there a way to prioritise my code so that it fires -before- the Paypal code?
EDIT: I added e.preventDefault() per the first answer, but what that does is:
a) the popup window still opens but
b) the Paypal site is never reached.
Instead, it displays the calling page in the popup.
So... I want to prevent that Paypal popup window from opening. Perhaps I need to change the 'action' on the form and trigger that action from inside my jQuery? If so, how do I do this?
Look into the preventDefault() function:
jQuery('#buyLink').click( function(event) {
event.preventDefault();
if (jQuery("#buysongs input:checkbox:checked").length == 0) {
alert('Please select at least one song!');
return false;
}
else{
// submit form
}
});

How to prevent navigation by browser buttons but not by links?

I want warn users if they leave the page by closing the browser or using the history buttons of the browser using the following javascript:
window.onbeforeunload = function(e) {
return 'Ask user a page leaving question here';
};
But my links and buttons on my website should work regardless of this. How can I achieve that?
The first way that comes to mind is to set a variable that tells you whether a link was clicked:
var linked = false;
window.onbeforeunload = function(e) {
if (!linked)
return 'Ask user a page leaving question here';
};
document.addEventListener('click', function(e) {
if (e.target.tagName === "A")
linked = true;
}, false);
That is, set a click event handler at the document level, that tests whether the clicked element was an anchor (or whatever else you want to allow) and if so sets the variable. (Obviously this assumes that you don't have other anchor element click handlers at a lower level that stop event propagation.)
var linkClicked = false;
window.onbeforeunload = function(e) {
if (!linkClicked){
linkClicked = false;
return 'Ask user a page leaving question here';
}
};
$(document).ready(function(){
$('a').click(function(e){
linkClicked = true;
});
});
Obviously this relies on JQuery to add the event handler to all links, but you could attach the handler with any other method, including adding onclick="linkClicked=true;" to every link on the page if you really have to.
Edit:
Just want to point out that if the user clicks a link that doesn't redirect them (e.g. a hashtag link to somewhere else on the page, or something that returns false / prevents the default action being executed) then this will set linkClicked to true and subsequently any browser based navigation won't be caught.
If you want to catch this, I would advise setting a timeout on the link click like so:
$(document).ready(function(){
$('a').click(function(e){
linkClicked = true;
setTimeout(function(){
linkClicked = false;
}, 500);
});
});
This will allow half a second for the window unload event to trigger before resetting the flag so that future navigation events are caught correctly. This still isn't perfect, but it probably doesn't need to be.
You can use the window.onbeforeunload event.
var check= false;
window.onbeforeunload = function () {
if (!check) {
return "Are you sure you want to leave this page?"
}
}
function CheckBackButton() {
check= true;
}
referenceElement.addEventListener('onClick', CheckBackButton(), false);
Us a confirmation prompt no?
like this? Intercept page exit event
window.onbeforeunload = function (e) {
var message = "Your confirmation message goes here.",
e = e || window.event;
// For IE and Firefox
if (e) {
e.returnValue = message;
}
// For Safari
return message;
};
How to show the “Are you sure you want to navigate away from this page?” when changes committed? this may solve your problem How

Stop user from leaving web page, except for when submitting form

To stop the user from leaving my page, I'm using this javascript:
window.onbeforeunload = function()
{
if($('textarea#usermessage').val() != '')
{
return "You have started writing a message.";
}
};
This shows a message warning the user not to leave the page because they've started writing a message but not submitted. This shows up to save the user from losing this data.
Now, how can I stop this message from showing up when the form is submitted?
function handleWindowLeaving(message, form) {
$(window).bind('beforeunload', function (event) {
return message;
});
$(form).bind('submit', function () {
$(window).unbind('beforeunload');
});
};
when calling this, pass your message and the form reference, and it will automatically remove onbeforeunload when submitting the form. Otherwise, show message to user
Set a flag in your form's submit handler; check whether the flag is set in your unload handler. If it is - voila, it's a form submit!

Categories