Document: hasFocus() メソッド

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

hasFocus()Document インターフェイスのメソッドで、文書または文書内の何れかの要素がフォーカスを持っているかどうかを示す論理値を返します。 このメソッドは、文書内のアクティブな要素がフォーカスを持っているかどうかを特定するために使用することができます。

メモ: 文書を見ている時、文書内でフォーカスを持つ要素は常にアクティブ要素ですが、アクティブ要素がフォーカスを持っているとは限りません。 例えば、フォアグラウンドになっていないポップアップウィンドウ内のアクティブ要素はフォーカスを持ちません。

構文

js
hasFocus()

引数

なし。

返値

文書内のアクティブ要素にフォーカスがない場合は false を返します。 文書内のアクティブ要素にフォーカスがある場合は true を返します。

この例は、文書がフォーカスを持っているかどうかを検査します。 checkPageFocus() という関数は、document.hasFocus() の結果に応じて段落要素を更新します。 新しいウィンドウを開くと文書からフォーカスがなくなり、元のウィンドウに戻すとフォーカスが回復します。

HTML

html
<p id="log">フォーカスのチェック結果はこちらに表示されます。</p>
<button id="newWindow">新しいウィンドウを開く</button>

JavaScript

js
const body = document.querySelector("body");
const log = document.getElementById("log");

function checkDocumentFocus() {
  if (document.hasFocus()) {
    log.textContent = "この文書にフォーカスがあります。";
    body.style.background = "white";
  } else {
    log.textContent = "この文書にはフォーカスがありません。";
    body.style.background = "gray";
  }
}

function openWindow() {
  window.open(
    "https://developer.mozilla.org/",
    "MDN",
    "width=640,height=320,left=150,top=150",
  );
}

document.getElementById("newWindow").addEventListener("click", openWindow);
setInterval(checkDocumentFocus, 300);

結果

仕様書

Specification
HTML
# dom-document-hasfocus-dev

ブラウザーの互換性

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
hasFocus

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support
Partial support
Partial support
Has more compatibility info.

関連情報