Skip to content

Instantly share code, notes, and snippets.

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
(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 {
// 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);
}, {'once': true});
// When the form is submitted, delete the localStorage key/value pair.
textarea.form.addEventListener('submit', function() {
win.removeEventListener(unloadEvent, updateStorage);
}(this, this.document));

This comment has been minimized.

Copy link
Owner Author

@davidbgk davidbgk commented Oct 14, 2020

Related blog entry:

(one day, Github will allow to fork comments too :) )

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