Home > Back-end >  prevent opening an html file on multiple browser tabs
prevent opening an html file on multiple browser tabs

Time:01-04

I have an html file. I don't want to open that file too many times in one browser. if in the browser I already have that html file open. then when opening another tab with the same htm file, an error will appear. Is there any way to do that?. we can use javascript, html, jquery or any other way.

CodePudding user response:

The only reliable way I can see to do this is to listen to a message asking "Am I here?" on a BroadcastChannel and respond with "I am here.". At page load, ask "Am I here?" and if you get the positive response, you'll know another tab already has your page.

const bc = new BroadcastChannel("Tin huynh's Broadcast Channel");
const question = "Am I here?"
const answer = "I am here."
bc.onmessage = evt => {
  if (evt.data === question) {
    bc.postMessage(answer)
  } else if (evt.data === answer) {
    alert("I am already here.")
  }
}
bc.postMessage(question)

CodePudding user response:

You could store the number of open tabs in localStorage, then decrement the value when the tab closes:

const open =  localStorage.getItem('open') || 0

if(open > 0) document.write('Tab already opened')
localStorage.setItem("open", open   1)

window.addEventListener('unload', () => {
    localStorage.setItem('open', ( localStorage.getItem('open') - 1 || 0))
})

see it in action

CodePudding user response:

You can use JavaScript to check if the HTML file is already open in the browser before opening it in a new tab.

function openHTMLFile() {
  var isFileOpen = false;
  for (var i = 0; i < window.length; i  ) {
    if (window[i].location.href == "https://yoursite/path/to/file.html") {
      isFileOpen = true;
      break;
    }
  }


  if (!isFileOpen) {
    window.open("https://yoursite/path/to/file.html", "_blank");
  }
}
  • Related