js save data on page unload does not work as expected

79 Views Asked by At

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

1

There are 1 best solutions below

1
aldison On BEST ANSWER

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()">