Sanket Kale
Sanket Kale

Reputation: 33

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

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!!

Upvotes: 1

Views: 2045

Answers (1)

Ian
Ian

Reputation: 50905

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.

Upvotes: 1

Related Questions