Thursday, 15 April 2010

javascript - Save before unload -



javascript - Save before unload -

i'm having application interactive canvas , want save changes on it, before user exits page.

my approach function savebeforeunload(){ if (confirm('do want save current state clipboard?')) { /*yes*/ if (canvas.getobjects("rect").length > 0){ localstorage.setitem("clipboard_unfinishedconfig", json.stringify(canvas.tojson(customproperties))); return; /*no:*/ } else { localstorage.setitem("clipboard_unfinishedconfig", ""); return; } }

i phone call by

window.onbeforeunload = savebeforeunload;

what need accomplish yes/no confirmation, if user wants ovverride localstorage item current configuration.

problem

with code, confirm not appear. accordingly localstorage empty... console says "blocked confirm..."

approach - i explanation:

window.onbeforeload executes whatever in handler cares homecoming statement shall used confirmation message. , ofcourse can't alter button labels. 1 time onbeforeunload dialog shown blocks everything(that's why prompt blocked). in next code doing scheduling save using settimeout giving 0 milliseconds, added event loop.

now if user decides close tab anyway settimeout handler never runs, chooses remain handler runs & changes saved.

well, can following:

function savechanges () { localstorage.setitem("clipboard_unfinishedconfig", json.stringify(canvas.tojson(customproperties))); alert("changes saved !"); window.onbeforeunload = null; } function exitconfirmation () { settimeout( savechanges, 0 ); homecoming "there unsaved changes on canvas, changes lost if exit !"; } window.onbeforeunload = exitconfirmation(); //basically set whenever user makes changes canvas. 1 time changes saved window.onbeforeunload set null.

so, if user chooses remain back, changes saved,

this working solution, not best user experience in opinion, suggest maintain auto saving changes user makes & give button reset canvas if required. should not save on every single change, instead maintain auto saving in specific interval of time. if user tries close between interval show dialog saying "you have pending changes left".

approach - ii ( way ) function saveconfirmation () { if (confirm('do want save current state clipboard?')) { if (canvas.getobjects("rect").length > 0){ localstorage.setitem("clipboard_unfinishedconfig", json.stringify(canvas.tojson(customproperties))); } else { localstorage.setitem("clipboard_unfinishedconfig", ""); return; } } } function savebeforeunload(){ settimeout( saveconfirmation, 0 ); homecoming "you have unsaved changes"; } window.onbeforeunload = savebeforeunload;

but many nagging dialogs.

hope helps.

javascript confirm

No comments:

Post a Comment