Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: suppress "This page is asking you to confirm that you want to leave" popup on onbeforeunload

When a user leaves a page, I need to ask him if he wants to perform a particular action before leaving.

<script type="text/javascript">
$(document).ready(function() {
        window.onbeforeunload = askConfirm;
});

function askConfirm() {
    var addFriend = confirm("Would you like to ping?");
    if (addFriend) {
        var xmlhttp;
        if (window.XMLHttpRequest) {
            xmlhttp=new XMLHttpRequest();
        } else {
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.open("GET","http://example.com?ping=1234",true);
        xmlhttp.send();
    }
    return null;
}

Depending on the value of that last return statement ("", null, true, false, or not having a return statement at all) I can have one of two situations:

1) The user gets the "Would you like to ping?" confirmation (good), the ping is sent (good), and the user is presented with a "This page is asking you to confirm that you want to leave" popup (BAD).

-or-

2) The user gets the "Would you like to ping?" confirmation (good), the ping is not sent (BAD), and the user is not presented with a "This page is asking you to confirm that you want to leave" popup (good).

How can I have the AJAX ping sent, yet suppress the "This page is asking you to confirm that you want to leave" popup?

Edit: As ridiculous as it sounds, the "work around" that I found for this issue is to alert() after the xmlhttp.send() statement. The only clean way to do that is to alert the user that his ping has been sent. If future StackOverflowers find a better solution, I would love to know.

Thanks.

like image 628
dotancohen Avatar asked Feb 09 '12 22:02

dotancohen


2 Answers

You can make your Ajax request synchronous.

xmlhttp.open("GET","http://example.com?ping=1234", false); // use false here 
xmlhttp.send(); 

It might cause a slight delay if your server is slow, but it should solve the problem of the ping not being sent.

like image 165
gilly3 Avatar answered Sep 22 '22 00:09

gilly3


well instead of doing it before you leave, I did it onunload and here is what I got to work in FF and IE (besides chrome, that's all I got): http://jsfiddle.net/rmpLm/9/.

perhaps you can get it to work on chrome, but if you cant, maybe you could make it so that if you hit ok, it takes you to a page where you send it. hope it helps : )

EDIT: maybe you should consider making it so it does it onload

like image 44
Lysol Avatar answered Sep 22 '22 00:09

Lysol