0

I made a script which is used for checking unread notification. And it must be worked across all screen so it has been written in header of my project and it works well. Since it has been written in header,here i want to avoid it if i open more than one tab which means this process should be checked at one tab only even though more than one tab opens at a time.

window.onload=function(){
  fnCheckOrdStaNoti();

  setInterval(fnCheckOrdStaNoti, 15000);
}

function fnCheckOrdStaNoti(){
  $.ajax({
    url: 'notification.php',
    type: 'post',
    dataType: 'html',
    crossDomain: true,
    
    success: function(hdata) {
     // hdata has some information regarding notification
     // based on result i trigger another ajax function.
     // here i have to check how many no of browser tab has been opened with respect to my project. and have to be triggered another ajax function to the first tab only, rest should be restricted.
    },
    error: function(xhr, ajaxOptions, thrownError) {
      console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
    }
  });
}
  • 2
    See e.g. https://blog.arnellebalane.com/sending-data-across-different-browser-tabs-6225daac93ec – luk2302 Apr 12 '21 at 07:25
  • 2
    You can use localStorage or a cookie to set a flag if the script is already active. This flag will be accessible for all tabs and all browser windows on the same domain. You'll also need to detect when that first window or tab gets closed, make it turn off the flag, and then any of the other open tabs can take over its function (that might actually be the trickiest part). *Update:* looks like the other commenters might have better solutions :-) – Peter B Apr 12 '21 at 07:28
  • Based on your use case, you might also be interested in [Web sockets](https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API). – Ivar Apr 12 '21 at 07:29
  • Thanks for you reply @PeterB. Using localStorage or cookie is fine. But how to detect browser tab like first tab/active tab ..etc.,. I have been suggested to use Tab api. But i vague because of i am new with this. – Peer Mohaideen Apr 12 '21 at 07:37
  • Have you checked @luk2302 link, as that appears to be exactly what you're after. – Keith Apr 12 '21 at 07:49
  • Thanks for your reply @Keith. I refered luk2302's link. It was nice but In my requirement i don't want to communicate with tabs. Here I just want to get browser tabs counts and also detect first tabs. That's enough for me. – Peer Mohaideen Apr 12 '21 at 08:55

1 Answers1

0

Finally, i found the solution for my problem. I have referred @Reza Amya's suggestion from this url. I have altered it for my requirement.