I have a scenario that prevents the same website in multiple opened tab pages of browser. My idea is when user open a website at first time from browser, it's fine, when user produces the new tab page or external link to open the same website again, we should redirect it to already opened one. I have no idea how to implement. Can I have some clues? Thanks.
Asked
Active
Viewed 1.4k times
2

Jan Dörrenhaus
- 6,581
- 2
- 34
- 45

crazy_develerper
- 107
- 1
- 1
- 8
-
"we should redirect it to already opened one" --- what does this exactly mean? – zerkms Nov 18 '15 at 00:01
-
https://github.com/tejacques/crosstab + `window.focus()` – qwertymk Nov 18 '15 at 00:02
-
not open more than one tab page for same website – crazy_develerper Nov 18 '15 at 00:13
-
1You cannot (and should not) do that. – zerkms Nov 18 '15 at 00:13
-
User can always just open use another browser or another computer to open another view onto the web site. So, basically you cannot ever prevent this. Your web-site should be able to handle multiple tabs viewing the same state. – jfriend00 Nov 18 '15 at 00:22
-
Currently, I just want to implement within same browser. Not worried about different browsers. – crazy_develerper Nov 18 '15 at 00:41
2 Answers
4
Perhaps use local storage.
Window.onload=function(){
if(localStorage.getItem('windows')===1){
window.close();
}else{
localStorage.setItem("windows",1);
}
}
Window.onbeforeunload=function(){
localStorage.setItem("windows",0);
}

Joshua Herreid
- 41
- 1
- 4
-
2So if for some reason `onbeforeunload` was not triggered - a user would never be able to open the site? – zerkms Nov 18 '15 at 00:14
-
-
And, if your browser ever crashes or the computer shuts down abruptly, so the localStorage item is not cleared, you can never get your page open again. Not a good failure mode. – jfriend00 Nov 18 '15 at 00:23
-
4
I recently ran across a similar problem where I had to prevent that multiple windows/tabs operated on the same localStorage.
The solution was to use StorageEvents: every window receives a StorageEvent whenever another(!) window made changes to the same localStorage as this one uses.
Thus, the trick was to define a "dummy" key for localStorage and let every window write some random value into that key just to let all other windows using the same localStorage receive a StorageEvent:
window.addEventListener('storage', () => {
window.alert('another window or tab is working on the same localStorage')
}, false)
localStorage.setItem('Sentinel',Math.random())

Andreas Rozek
- 392
- 4
- 12