'Detect multiple tabs opening... and close the newest tabs! (via BroadcastChannel API)

I've put this function on load so I can detect a new tab being opened:

function checkNewTabs() {
  const channel = new BroadcastChannel('tab');
  channel.postMessage('newTab');
  channel.addEventListener('message', (msg) => {
    if (msg.data === 'newTab') {
      alert('Please don't open more than one tab at a time!');
      //window.open('', '_self', '').close();
    }
  });
}

I want to be able to send a message back to the new tab like this:

channel.postMessage('callbackNewTab');
channel.addEventListener('message', (msgBack) => {
  if (msgBack.data === 'callbackNewTab') {
    alert('This tab will be closed!');
    window.open('', '_self', '').close();
  }
});

In order to close the new tab...

I can do it for the old tab but what I really need is for it to close the new tab!

Can anyone help me out please? tks! :)



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source