skip to Main Content

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.

2

Answers


  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");
      }
    }
    
    Login or Signup to reply.
  2. 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)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search