Stimulus - Video Progress Tracker with LocalStorage

Store ephemeral user state like video playback progress in localStorage

Stimulus - Video Progress Tracker with LocalStorage

Premise

A lot of UX leverage lies in the way applications manage ephemeral user state. The traditional approach to store such data would be to reach for server side sessions. However, sometimes this is overshooting the target because it leads to more complexity on the server side, having to (de)serialize data structures and manage rehydration. Often, client-side localStorage provides a simpler alternative.

Starting Point

We are going to experiment with localStorage using an example containing three <video> elements on a page:

https://stackblitz.com/edit/stimulus-video-progress-tracker?file=index.html%3AL41

The goal is to store the playing progress for each video and restore it on page reload. Here’s a GIF showing this in action:

Video progress stored and restored after page reload

Challenge

In a video-progress Stimulus controller, write two actions:

  • recordProgress for storing the current time for each video in localStorage
  • #seekToProgress to restore the current time upon connect

As you can see, #seekToProgress is already called whenever the controller is connected. What’s missing is to fire the correct event and update the storage entry. For this, wire up it up in data-action:

https://stackblitz.com/edit/stimulus-video-progress-tracker?file=index.html%3AL49

Tip: Look at the Video Embed element docs for some clues.

Teasers

Suppose you want to store sensitive data in localStorage that you don’t want anyone to tamper with. What are your options?

More from

Stimulus - Image Upload Previews with `URL.createObjectURL`
17 September 2024

Create client-side previews of files using URL.createObjectURL

Stimulus - Removing Markers from a Wavesurfer Element
30 July 2024

Use Stimulus value callbacks to interact with a wavesurfer element and remove markers.

Stimulus - Adding Markers to a Wavesurfer Element
02 July 2024

Use Stimulus value callbacks to interact with a wavesurfer element and add markers.

Cookies
essential