<script>
// Broadcast that you're opening a page.
localStorage.openpages = Date.now();
window.addEventListener('storage',
function
(e) {
if
(e.key ==
"openpages"
) {
// Listen if anybody else is opening the same page!
localStorage.page_available = Date.now();
}
if
(e.key ==
"page_available"
) {
alert(
"One more page already open"
);
}
},
false
);
</script>
You might need to read the following steps 2 or 3 times to grab the concept properly.
- When you open the 1st tab, line # 3 will create a local storage value named “openpages”.
- Storage listener will NOT be called because the local storage value is updated from this tab.
- When you open the second tab, line # 3 will also create a local storage value named “openpages”.
- Storage listener from the 1st tab will be called because the local storage is updated from the 2nd tab.
- 1st tab will receive the value of “e.key” as “openpages”.
- So it will create another local storage value “page_available” at line # 7.
- Now this will call the storage listener from the 2nd tab. Because for the 2nd tab, it is called from the 1st tab.
- 2nd tab will receive the value of “e.key” as “page_available”, so it will display an alert message.
Ref: https://adnan-tech.com/detect-multiple-tabs-opened-at-same-time-javascript/
No comments:
Post a Comment