1

Specification:

  1. Show alert when user leaves pages.
  2. Perform action when user confirms "Leave this page" (send ajax request and wait until response is received).
  3. When ajax response is received then leave page.

My code is:

 window.onbeforeunload = function (e) {
     e = e || window.event;
     if (e) {
         e.returnValue = 'Sure?';
     }
     $.ajax({
         url: '/api/Electronic/leave',
         dataType: "json",
         contentType: "application/json",
         cache: false,
         type: 'POST',
         data: myData,
         success: function (data) {
             //how to leave this page?
         },
         error: function () {
             console.log("Error");
         }
     });
     return 'Sure?';
 };
ji-ruh
  • 725
  • 1
  • 7
  • 24
Irfan Y
  • 1,242
  • 2
  • 21
  • 68

2 Answers2

0

-You can do synchronous ajax call when the user leaves the page and wait the result

      window.onbeforeunload=function(e){        

        var result = false;
        $.ajax({
            url: 'https://api.github.com/users/mralexgray/repos',
            type: 'GET',
            async: false,
            success: function (data) {

                //do whatever you want here
                for (var i = 0; i < 10000;i++){
                    console.log(i);
                }                                 
                result = true;
            },
            error: function (e) {
                console.log("error");                  
            }
        });

        if (result) {
            window.onbeforeunload = window.thisPage.closeEditorWarning;
        } else {
            var confirmationMessage = 'Somthing went wrong. If you leave your changes will be lost.';

            (e || window.event).returnValue = confirmationMessage;              
             return confirmationMessage; 
        }


    }
Ahmed Al Jabry
  • 1,367
  • 13
  • 9
0

Perform action when user confirms "Leave this page" (send ajax request and wait until response is received).

That's not possible. When the user confirms "Leave this page" your script is terminated.

ハセン
  • 377
  • 3
  • 5