简体   繁体   中英

Javascript window.onbeforeunload not work without Alert

Hi I use javascript to save information after page going to be close or navigate to another page.My problem is when I call webservice in window.onbeforeunload it is not going to fire and I dont get result. But If I put alert at the end of function webservice going to fire and I get result.I don't want to use alert at all .Is there any way.my code is as follows:

    window.onbeforeunload = InitializeService;
     function InitializeService() {
        if (window.XMLHttpRequest) {

            var url = "http://localhost:54329/WebServices/PageUnloadCall.asmx?op=Page_Unload";

           myReq.onreadystatechange = checkStatus1;

           myReq.open("GET", url, true); // true indicates asynchronous request

           myReq.send();

      //     alert("Your Call Record Has Been Saved!");

     }
     }
     function checkStatus1() {

         if (myReq.readyState == 4) // Completed operation
         {

             myReq.open("POST", "http://localhost:54329/WebServices/PageUnloadCall.asmx/Page_Unload", false);

             myReq.send();

         }
     }

As you can see in function InitializeService ,I dont want to use Alert there but if I dont I dont get result.

That would be because the onbeforeunload is long gone (done, complete) before your webservice call returns. Your webservice call gets initiated and it probably reaches the server (check logs at server; add a log call to verify), but the browser decides not to wait - which is by design, because the user is navigating away from the page.

If your only goal is to report this event, you might be fine (as you're probably getting it), but if you intended to do anything AFTER, see if it'll work if you change the behavior of that service call to synchronous:

myReq.open("GET", url, false);

The alert is allowing the async call to finish allowing the response. Change:

myReq.open("GET", url, true);

to:

myReq.open("GET", url, false);

Try a synchronous request (don't know if it'll work):

myReq.open("GET", url, false); // false => synchronous request

Should cause the unbeforeunload handler to wait for the call to complete before returning, and letting the unload continue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM