LoginSignup
1
0

タブがアクティブかどうかでタイトルを変更する方法

Posted at

Akiflowのサイトで別タブを閲覧中の時、タイトルが「🥺 Come back」になっており、どのように実装しているのか気になって調べたのでご紹介します。

Akiflow閲覧中

スクリーンショット 2024-04-02 17.43.51.png

Akiflow閲覧してない

スクリーンショット 2024-04-02 17.43.56.png

コード

documentvisibilitychangeイベントで、タブのアクティブが変更されたか監視できます。
また、document.visibilityStateでタブがアクティブかどうか判別できます。

document.addEventListener('visibilitychange', () => {
  if (document.visibilityState === 'visible') {
    document.title = '閲覧中';
    return
  }

  document.title = '🥺 閲覧してない';
});

おまけ

上記方法とは少し違いますが、ウィンドウのフォーカスが変更された時の判別方法もご紹介します。

window.addEventListener('focus', () => {
  document.title = 'フォーカス中';
});

window.addEventListener('blur', () => {
  document.title = '🥺 フォーカス外れた';
});

まとめ

タブがアクティブかどうかで、タイトルを変更する方法をご紹介しました。
あまり使用するイベントでは無いですが、ユーザーが閲覧してない時に重い処理を止めたい場合などに有効かなと思いました。

参考サイト

最後に

GoQSystemでは一緒に働いてくれる仲間を募集中です!

ご興味がある方は以下リンクよりご確認ください。

1
0
0

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
0