Last active
June 22, 2019 09:58
-
-
Save sumartoyo/edc34f48c3e04d76316450ecc008cab6 to your computer and use it in GitHub Desktop.
Choosing one tab to run a task when multiple tabs are opened
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<body> | |
<pre>open console</pre> | |
<script> | |
const ID_TAB = `${Math.random()}`; | |
const KEY_PREFIX = `handlerSomething-`; | |
const KEY_SELF = `${KEY_PREFIX}${ID_TAB}`; | |
function main() { | |
console.log(`you are ${ID_TAB}`); | |
registerHandler(); | |
window.addEventListener('beforeunload', unregisterHandler); | |
} | |
function registerHandler() { | |
window.localStorage.setItem(KEY_SELF, ID_TAB); | |
} | |
function unregisterHandler() { | |
window.localStorage.removeItem(KEY_SELF); | |
} | |
function checkHandler() { | |
let keyWinner = null; | |
for (let key of Object.keys(window.localStorage)) { | |
if (key.startsWith(KEY_PREFIX)) { | |
if (keyWinner === null || key < keyWinner) { | |
keyWinner = key; | |
} | |
} | |
} | |
if (keyWinner === KEY_SELF) { | |
console.log(`yes, you are the handler`); | |
return true; | |
} else { | |
console.log(`no, not you, the handler is ${window.localStorage.getItem(keyWinner)}`); | |
return false; | |
} | |
} | |
main(); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Consider this example. Your app listen to an event (possibly from server) and perform a task when the event is emitted. When the app is opened in multiple tabs, the task must only run in one tab and other tabs must not run the task.
Instead of choosing one tab to listen to the event, I decided to let all tabs listen to the event but only allow one tab to run the task. When the event is emitted, every tab perform
checkHandler
to check if the runner of the task is itself. The check is safe even when the event is arrived at the same time in all tabs.