Tin huynh
Tin huynh

Reputation: 35

prevent opening an html file on multiple browser tabs

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.

Upvotes: 0

Views: 194

Answers (2)

Cristiano Ronaldo
Cristiano Ronaldo

Reputation: 1

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

Upvotes: -1

Amadan
Amadan

Reputation: 198388

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)

Upvotes: 2

Related Questions