javascript beforeunload not modifying data

125 views Asked by At

Script evaluates onbeforeunload, saves to local storage but here is my problem: it does not alter any arrays or objects nor does it allow any new variables.

This gets in the way when I have objects I need to modify before saving them to local storage.

It seems like a limitation of JavaScript (since alerts are not triggered as well).

Is there any way to get arround this?

var saved = { hello: "world" };
var anArray = ["default"];

saveData = function ()
{
    console.warn('Saving data...');

    saved['test'] = true;
    anArray.push('something');

    localStorage.setItem('test', 'somedata');

    console.debug(saved);
    console.debug(anArray);

    window.onbeforeunload = null;
    console.warn('Done saving...');

    return true;
}

proxySave = function ()
{
    setTimeout(saveData, 0);
    return;
}

window.onbeforeunload = proxySave;
1

There are 1 answers

1
T.J. Crowder On

The setTimeout means the code doesn't run during the onbeforeunload, meaning all bets are off. If you want to do something during onbeforeunload, do it during onbeforeunload:

window.onbeforeunload = saveData;

(And remove the return true in saveData.)

Yes, there are limits on what you can do in onbeforeunload, but basic object manipulation isn't one of them.