I am writing some code currently being tested on localhost. The URL of one page that I am working on changes occasionally to add something after the #
sign. For example,
It will change from:
http://localhost/something.php#/4
to
http://localhost/something.php#/5
I want the other page open in the second monitor of the same PC with URL http://localhost/anything.php
to know about it.
My first thought to do this was with a setInterval
that would regularly check the localStorage
for the current URL of the something.php
page.
Is there a more efficient way of doing this so that I don’t have to make frequent checks with setInterval
?
Can the something.php
page beam its status of being changed to the other page whenever the URL change happens?
Thanks.
Advertisement
Answer
Listen for the hashchange event and send a message over a BroadcastChannel.
const bc = new BroadcastChannel("location"); window.addEventListener('hashchange', () => { bc.postMessage(location.hash) }) bc.addEventListener('message', function(e){ location.hash = e.data; }) window.addEventListener('beforeunload', () => bc.close())