0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

window.focus / window.blur の意味

0
Posted at

Windowのfocus/blur

バイブコーディングをしていた際に、「ブラウザを切り替えたら再レンダリング」される現象があり、その事象を何と言うのか分からなかった。

調べると、「window.focus/blur」で通じるようだったので備忘録。

window.focus/blur

window.focus / window.blur は メソッド と イベント の両方が存在する。
タブ切り替え検知で使うのは イベントのほう。

window.focus イベント

ブラウザのタブやウィンドウにユーザーが戻ってきたときに発火。

window.blur イベント

ユーザーがタブやウィンドウを離れたりときに発火。

サンプルコード

window.addEventListener("focus", () => {
  console.log("タブに戻ってきた!");
});

window.addEventListener("blur", () => {
  console.log("タブから離れた!");
});

📌 使いどころ

  • チャットアプリ:タブがアクティブなときだけ「既読」にする
  • ゲーム:ユーザーがタブを離れたら自動でポーズする
  • 省リソース:タブが非アクティブのときはアニメーションやポーリングを止める

まとめ

window の focus / blur は 「ページ全体が見られているかどうか」 を判定するためのイベント。

0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?