2

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.

Jan Dörrenhaus
  • 6,581
  • 2
  • 34
  • 45
crazy_develerper
  • 107
  • 1
  • 1
  • 8

2 Answers2

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);
}
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