Svelte and Localstorage remote
Domenik Reitzner
Posted on April 12, 2021
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>
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}
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 š
- website
- repo
- Photo by Kelly Sikkema
Posted on April 12, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.