Search code examples
javascriptphphtmlonbeforeunload

How to execute a js function on pageunload


I'm making a little game, and I want to save the score when the user leaves the page, I want to do this without jquery or another library, is this possible?

I save the score by executing a javascript function that creates a form and automatically submits it, so it's data is being send to the server:

function sendData() {
    var form = document.createElement("form");
    form.setAttribute("method","post");
    form.setAttribute("action", "submit.php");
    form.setAttribute("id","returnForm");

      var formContent1 = document.createElement("input");
      formContent1.setAttribute("name","gamesPlayed");
      formContent1.value = gamesPlayed;  //parameter 1

      var formContent2 = document.createElement("input");
      formContent2.setAttribute("name","totalSteps");
      formContent2.value = totalTurns;   //parameter 2 

    form.appendChild(formContent1);
    form.appendChild(formContent2);
  document.body.appendChild(form);
  document.getElementById("returnForm").submit();
}

I found a few things such as, this function will pop up a window with 'are you really sure you want to leave this page',

  window.onbeforeunload = function(e) {
    return false; 
  }

But when I try to put my 'sendData()' function in it, it doesn't work:

  window.onbeforeunload = function(e) {
    sendData();
  }

Even if I put the entire function in it:

  window.onbeforeunload = function(e) {
      var form = document.createElement("form");
      form.setAttribute("method","post");
      form.setAttribute("action", "submit.php");
      form.setAttribute("id","returnForm");

        var formContent1 = document.createElement("input");
        formContent1.setAttribute("name","gamesPlayed");
        formContent1.value = gamesPlayed;  //parameter 1

        var formContent2 = document.createElement("input");
        formContent2.setAttribute("name","totalSteps");
        formContent2.value = totalTurns;   //parameter 2 

      form.appendChild(formContent1);
      form.appendChild(formContent2);
    document.body.appendChild(form);
    document.getElementById("returnForm").submit();
  }

Solution

  • Use onunload event in javascript like in this article.

    window.onbeforeunload = function(e) {
        return 'Are you sure ?'; 
      }
    
    window.onunload = function () {
     sendData();
    }