Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Put the contents of a textarea into localStorage if the user leaves the page before submitting the form.
// Licensed under a CC0 1.0 Universal (CC0 1.0) Public Domain Dedication
// http://creativecommons.org/publicdomain/zero/1.0/
(function (win, doc) {
// Cut the mustard.
if (!win.localStorage) return;
// You should probably use a more specific selector than this.
var textarea = doc.querySelector('textarea');
// The key for the key/value pair in localStorage is the current URL.
var key = win.location.href;
var item = null;
// Use the 'pagehide' event in modern browsers or 'beforeunload' in older browsers.
var unloadEvent;
if ('onpagehide' in win) {
unloadEvent = 'pagehide';
} else {
unloadEvent = 'beforeunload';
}
// If there's a localStorage entry for the current URL, update the textarea with the saved value.
item = win.localStorage.getItem(key);
if (item) {
var data = JSON.parse(item);
textarea.value = data.content;
}
// This function will store the current value of the textarea in localStorage (or delete it if the textarea is blank).
function updateStorage() {
if (textarea.value) {
item = JSON.stringify({'content': textarea.value});
win.localStorage.setItem(key, item);
} else {
win.localStorage.removeItem(key);
}
// This event listener is no longer needed now so remove it.
win.removeEventListener(unloadEvent, updateStorage);
}
// When the user presses a key just *once* inside the textarea, run the storage function when the page is unloaded.
textarea.addEventListener('keyup', function() {
win.addEventListener(unloadEvent, updateStorage);
win.setInterva(updateStorage, 60000);
}, {'once': true});
// When the form is submitted, delete the localStorage key/value pair.
textarea.form.addEventListener('submit', function() {
win.localStorage.removeItem(key);
win.removeEventListener(unloadEvent, updateStorage);
});
}(this, this.document));
@adactio

This comment has been minimized.

Copy link
Owner Author

@adactio adactio commented Oct 14, 2020

Blog post: Saving forms.

@justmarkup

This comment has been minimized.

Copy link

@justmarkup justmarkup commented Oct 15, 2020

@adactio Clever, I like it. One thing I want to note here - you should never use localstorage.setItem() or removeItem() outside a try/catch block, as in some browsers in incognito mode this will throw an exception. I once had this issue on Safari on iOS in incognito mode and took my quite some time to find that while "localStorage" in window returns true, you can't use setItem()/removeItem() there.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.