LoginSignup
1
2

More than 1 year has passed since last update.

ブラウザのタブの複製を検知する

Posted at

アプリケーションで、あるタブから別のタブを複製して欲しくないときがあります(ひとつのタブだけ)

これまではCockieとか使ってたみたいなのですが、最近のブラウザであればブロードキャストをつかってかけそうです。

これで、複製すると元のタブのBodyを潰せます(クローズまでは出来ません)

const channel = new BroadcastChannel('tab');
channel.postMessage('another-tab');
channel.addEventListener('message', (event) => {
    if (event.data === 'another-tab') {
        document.body.innerHTML = `新しいタブが開かれたためクローズしました。`;
    }
});

いま開いたタブを検知したい場合は……実はよく分かりません。イベントにイベントを返せば元のタブにレスポンス返せると思い次のように書いたのですが、event.sourceがnullですとか言われてエラーになります。

const channel = new BroadcastChannel('tab');
channel.postMessage('another-tab');
channel.addEventListener('message', (event) => {
    if (event.data === 'another-tab') {
        event.source.postMessage("another-tab-response");
    }else if(event.data === 'another-tab-response'){
        document.body.innerHTML = `このサイトではタブの複製は禁止されています。`;
    }
});
1
2
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2