Svelte and Localstorage remote

dreitzner

Domenik Reitzner

Posted on April 12, 2021

Svelte and Localstorage remote

Idea šŸ’”

localStorage is a very versatile part of web development for persisting data, but it can do so much more.

Every change fires a storage event on the window Object across tabs, which means it can be used as remote. šŸ¤Æ

Potential uses šŸ› 

  • Video controller in a small popup window
  • Speaker view of presentation slides

Implementation āš—

I used svelte-kit for the example (see links) šŸ˜‰
The actual amount of code needed for this pattern is very minimalistic. On the remote side we only need to set a localStorage item and this in turn will trigger the event which we can listen to.

<button
  on:click={() => localStorage.setItem('signal', 'message')}>
  Set 'message'
</button>
Enter fullscreen mode Exit fullscreen mode

The receiver is a little more work, but svelte is our friend and helper šŸ’Ŗ

<script>
  let signal = '';
  const listener = () => {
    const value = localStorage.getItem('signal');
    if (!value) return;
    signal = value;
  };
</script>
<svelte:window on:storage={listener} />

Received Signal: {signal}
Enter fullscreen mode Exit fullscreen mode

If you open the remote and the receiver (same browser and base URL) you should be able to send and receive signals across tabs without any network request.

āš  because of security issues localStorage is blocked on the svelte REPL, so it will not work there

I hope you found this entry interesting and learned something new ā˜ŗ

Links šŸ”—

šŸ’– šŸ’Ŗ šŸ™… šŸš©
dreitzner
Domenik Reitzner

Posted on April 12, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Svelte and Localstorage remote
svelte Svelte and Localstorage remote

April 12, 2021