Saving forms

I added a long-overdue enhancement to The Session recently. Here’s the scenario…

You’re on a web page with a comment form. You type your well-considered thoughts into a textarea field. But then something happens. Maybe you accidentally navigate away from the page or maybe your network connection goes down right when you try to submit the form.

This is a textbook case for storing data locally on the user’s device …at least until it has safely been transmitted to the server. So that’s what I set about doing.

My first decision was choosing how to store the data locally. There are multiple APIs available: sessionStorage, IndexedDB, localStorage. It was clear that sessionStorage wasn’t right for this particular use case: I needed the data to be saved across browser sessions. So it was down to IndexedDB or localStorage. IndexedDB is the more versatile and powerful—because it’s asynchronous—but localStorage is nice and straightforward so I decided on that. I’m not sure if that was the right decision though.

Alright, so I’m going to store the contents of a form in localStorage. It accepts key/value pairs. I’ll make the key the current URL. The value will be the contents of that textarea. I can store other form fields too. Even though localStorage technically only stores one value, that value can be a JSON object so in reality you can store multiple values with one key (just remember to parse the JSON when you retrieve it).

Now I know what I’m going to store (the textarea contents) and how I’m going to store it (localStorage). The next question is when should I do it?

I could play it safe and store the comment whenever the user presses a key within the textarea. But that seems like overkill. It would be more efficient to only save when the user leaves the current page for any reason.

Alright then, I’ll use the unload event. No! Bad Jeremy! If I use that then the browser can’t reliably add the current page to the cache it uses for faster back-forwards navigations. The page life cycle is complicated.

So beforeunload then? Well, maybe. But modern browsers also support a pagehide event that looks like a better option.

In either case, just adding a listener for the event could screw up the caching of the page for back-forwards navigations. I should only listen for the event if I know that I need to store the contents of the textarea. And in order to know if the user has interacted with the textarea, I’m back to listening for key presses again.

But wait a minute! I don’t have to listen for every key press. If the user has typed anything, that’s enough for me. I only need to listen for the first key press in the textarea.

Handily, addEventListener accepts an object of options. One of those options is called “once”. If I set that to true, then the event listener is only fired once.

So I set up a cascade of event listeners. If the user types anything into the textarea, that fires an event listener (just once) that then adds the event listener for when the page is unloaded—and that’s when the textarea contents are put into localStorage.

I’ve abstracted my code into a gist. Here’s what it does:

  1. Cut the mustard. If this browser doesn’t support localStorage, bail out.
  2. Set the localStorage key to be the current URL.
  3. If there’s already an entry for the current URL, update the textarea with the value in localStorage.
  4. Write a function to store the contents of the textarea in localStorage but don’t call the function yet.
  5. The first time that a key is pressed inside the textarea, start listening for the page being unloaded.
  6. When the page is being unloaded, invoke that function that stores the contents of the textarea in localStorage.
  7. When the form is submitted, remove the entry in localStorage for the current URL.

That last step isn’t something I’m doing on The Session. Instead I’m relying on getting something back from the server to indicate that the form was successfully submitted. If you can do something like that, I’d recommend that instead of listening to the form submission event. After all, something could still go wrong between the form being submitted and the data being received by the server.

Still, this bit of code is better than nothing. Remember, it’s intended as an enhancement. You should be able to drop it into any project and improve the user experience a little bit. Ideally, no one will ever notice it’s there—it’s the kind of enhancement that only kicks in when something goes wrong. A little smidgen of resilient web design. A defensive enhancement.

Have you published a response to this? :

Responses

3 Likes

# Liked by Chris Taylor on Wednesday, October 14th, 2020 at 1:10pm

# Liked by George Salib® on Wednesday, October 14th, 2020 at 4:38pm

# Liked by Daria Czerniawko on Sunday, October 18th, 2020 at 2:50pm

Related posts

Three attributes for better web forms

Better UX through better HTML: inputmode, enterkeyhint, and autocomplete.

Accessibility testing

It’s not just about finding the issues—it’s about finding the issues at the right time.

Good form

Science, the web, and user experience.

Authentication

Some ways of combining security and usability for two-factor authentication on the web.

Web Forms: Now You See Them, Now You Don’t! by Jason Grigsby

A presentation at An Event Apart Chicago 2019.

Related links

Bring Focus to the First Form Field with an Error :: Aaron Gustafson

A handy little script from Aaron to improve the form validation experience.

Tagged with

Build a Better Mobile Input

This is such a handy tool for building forms! Choose different combinations of type, inputmode, and autocomplete attributes on input elements and see how that will be conveyed to users on iOS and Android devices.

Tagged with

Simple things are complicated: making a show password option - Technology in government

This is a great deep dive into a single component, a password toggle in this case. It shows how assumptions are challenged and different circumstances are considered in order to make it truly resilient.

Tagged with

Reflecting on My Own Experience Using the Web to Get the Vaccine - Jim Nielsen’s Blog

I click the link. The page loads fast. I navigate the surprisingly sparse yet clear form inputs. And complete the whole thing in less than thirty seconds.

Oh, how I wish this experience weren’t remarkable!

Simple forms with clear labels. Little to no branding being shoved down my throat. No array of colors, big logos, or overly-customized UI components.

Tagged with

HTML Forms: How (and Why) to Prevent Double Form Submissions – Bram.us

I can see how this would be good to have fixed at the browser level.

Tagged with

Previously on this day

5 years ago I wrote Something for the weekend

Science Hack Day in San Francisco and Indie Web Camp in Brighton

10 years ago I wrote Celebrating CSS

Here’s to the next twenty years.

11 years ago I wrote Listen to dConstruct 2013

For your huffduffing pleasure.

15 years ago I wrote Optimisation

Optimise for ugly bags of mostly water, not your plastic pal that’s fun to be with.

17 years ago I wrote Semantic brevity

Make microformats work with your writing style.

23 years ago I wrote The roots of conflict

Here’s some more grist for the fundamentalist mill.

23 years ago I wrote Falwell-Robertson-Bin Laden Quiz

This is too perfect.