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
Top comments (0)