1

Is it possible to fire an alert on browser close? If user confirm "reload/close" then want to execute some ajax stuff. This is I have tried so far

window.onbeforeunload = function () {
    return 'This will close your chat session. Are you Sure!';
    var meta_id = $('#meta_id').val();
    $.ajax({
        url: site_url + '/chat/send_offline',
        type: 'post',
        cache: false,
        async: false,
        data: {
            meta_id: meta_id
        }
    });
}

As far I know code not execute after the return statement. So is it possible to alert and execute ajax code simultaneously if user confirm??

Rejoanul Alam
  • 5,435
  • 3
  • 39
  • 68

2 Answers2

0

I found this in MDN documentation

window.addEventListener("beforeunload", function (e) {
  var confirmationMessage = "Do you want to leave this page ?";

  // Call AJAX RIGHT HERE

  e.returnValue = confirmationMessage;     // Gecko and Trident
  return confirmationMessage;              // Gecko and WebKit
});

You have to call the Ajax before return in the function. Because return break the execution of the function.

I'm_ADR
  • 1,017
  • 8
  • 15
  • This will not solve the issue because if user close browser and alert message shown after ajax call then all action will be wrong (if user cancel the browser close) – Rejoanul Alam Sep 10 '15 at 07:04
  • It seems that is not possible to catch the anwser of the user. [link](http://stackoverflow.com/a/5400059/4547547) But you can use the unload event to make your Ajax call ! https://developer.mozilla.org/en-US/docs/Web/Events/unload – I'm_ADR Sep 10 '15 at 07:14
-1

Maybe chrome.runtime.onSuspend or chrome.windows.onRemoved will help you?