javascriptdatabasesaveonbeforeunloadonunload

js save data on page unload does not work as expected


Im trying to save some data on page unload, this is my current script

window.addEventListener("unload", function(event) {
    if(snippetChanged){
        //save it
        snippetChanged = false
        var changeData = {
            code: CryptoJS.AES.encrypt(snippetEditor.getValue(), 'key').toString(),
            name: path[0]
        }
        var xmlHttp = new XMLHttpRequest();

        xmlHttp.open('POST', '/userhome/updateSnippet', true);
        xmlHttp.send(JSON.stringify(changeData)); 
    }
})

however this only works partially (resetting the webpage in firefox), I have no clue why this is happening, any help would be very much appreciated


Solution

  • Create a function and name it saveData()

    function saveData(){
       // your code to save the data
    }
    

    at the Body html tag put the onunload="saveData()" example:

    <body onunload="saveData()">