1

I need to add some codes before close browser tab/windows, or refresh browser. for example i need send students activity scores to database and stop all running timers if needed and also show an alert to students to show scores that they got.i used 'beforeunload' but it don't work for me

$(window).bind('beforeunload', function(e){
    $.ajax({
        type:'POST', 
        url: 'increaseScore.php',
        data: {personal_code: "414896521", lScore: 85},
        success: function(response) {
            alert("you have " + response + "Scores, now"); // show scores alert
        }
    }).promise().done(function() {
        clearInterval(); // clear all timers
    })
})

what is the way for do this actions before close the browser tab or reload browser? thanks a lot

MojtabaSh
  • 627
  • 1
  • 11
  • 26
  • Similar question - http://stackoverflow.com/questions/291553/is-there-a-way-in-javascript-to-detect-if-the-unload-event-is-caused-via-a-refre – khushboo29 May 05 '16 at 09:37
  • @user2947 so, do you think there is not any way for run codes before close browser? – MojtabaSh May 05 '16 at 09:44

1 Answers1

1

Yes you can. Try this:-

window.addEventListener("beforeunload", function (e) {
  var confirmationMessage = "\o/";

  (e || window.event).returnValue = confirmationMessage; //Gecko + IE
  return confirmationMessage;                            //Webkit, Safari, Chrome
});

I've not tries it in all browsers Or

window.onbeforeunload = function () {
    return "Do you really want to close?";
};

It should work too.

khushboo29
  • 906
  • 6
  • 16
  • Thanks @user2947 , It working in Chrome and Internet explorer, and also it work on firefox when the page/window closeing, but it don't work on firefox when the page refreshing , is there anywhy to do that? – MojtabaSh May 05 '16 at 13:26