Skip to content

Instantly share code, notes, and snippets.

@adactio
Last active December 2, 2023 06:52
Show Gist options
  • Save adactio/be3fb1e7c15a47a90f87c7df11158e2e to your computer and use it in GitHub Desktop.
Save adactio/be3fb1e7c15a47a90f87c7df11158e2e to your computer and use it in GitHub Desktop.
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
Copy link
Author

adactio commented Oct 14, 2020

Blog post: Saving forms.

@justmarkup
Copy link

@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.

@davidbgk
Copy link

An l (L letter) is missing on line 39 for the end of the setInterval() method.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment