MojtabaSh
MojtabaSh

Reputation: 637

how can run some codes before close browser tab/windows/refresh using Jquery

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

Upvotes: 1

Views: 719

Answers (1)

khushboo29
khushboo29

Reputation: 916

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.

Upvotes: 1

Related Questions