Casey Crookston
Casey Crookston

Reputation: 13945

Prevent 'Confirm Navigation' alert with window.location.href

I've got a button:

<button type="button" class="btn btn-primary mt15 send-emails" name="SendEmails" value="true">Send Emails</button>

And a method:

$('.send-emails').click(function (e) {
        // build data and other stuff
        $.post('/leads/sendemails', data, function (data, status, xhr) {
            alert('Emails have successfully been queued for sending.');
            window.onbeforeunload = null;
            window.location.href = '/Leads/Lead/' +  @Model.LeadID;
    }, 'json');
});

Even with window.onbeforeunload = null; I still get the popup warning:

enter image description here

How can I prevent this?

Upvotes: 2

Views: 2742

Answers (2)

jafarbtech
jafarbtech

Reputation: 7015

Use a global variable to check before redirecting to the page like this. Have a string variable to hold href which you need to redirect and redirect it before statement

(function($){
    var dontSubmit = false,
        $form = $('form#my-form');

    // Prevent the trigger a false submission on link click
    window.addEventListener("beforeunload", function (e) {
        dontSubmit = true;
        $form.trigger('submit');
    });

    $form.on('submit', function(event){
        if (dontSubmit) {
            event.preventDefault();
            return;
        }

        // Continue on as normal
    });
})(jQuery);

Upvotes: 0

Mihai Alexandru-Ionut
Mihai Alexandru-Ionut

Reputation: 48357

The solution is following:

$(window).unbind();

This will remove the onbeforeunload event just before redirect the browser to a new page using location.href.

Upvotes: 2

Related Questions