웹표준/Performance & Intergration
6. hasFocus()
부디이
2020. 4. 17. 20:01
- hasFocus() : 문서 내부의 요소에 초점이 있는지 여부를 나타내는 Document를 리턴한다. (true/false)
var focused = document.hasFocus(); //true, false 리턴
예제
다른 윈도우창을 띄워서 기존 페이지와 윈도우 팝업창을 각각 클릭하면서 포커싱이 어디로 되어있는지 확인.
<!--html-->
<p id="log">Awaiting focus check.</p>
<button onclick="openWindow()">Open a new window</button>
<!--js-->
<script>
function checkPageFocus() {
let body = document.querySelector('body');
let log = document.getElementById('log');
if (document.hasFocus()) {
log.textContent = 'This document has the focus.';
body.style.background = '#fff';
}
else {
log.textContent = 'This document does not have the focus.';
body.style.background = '#ccc';
}
}
function openWindow() {
window.open('https://developer.mozilla.org/', 'MDN', 'width=640,height=320,left=150,top=150');
}
// Check page focus every 300 milliseconds
setInterval(checkPageFocus, 300);
</script>