JavaScript:如何判斷瀏覽器標籤頁是否處於焦點狀態?
在本文中,我們將探討如何檢查瀏覽器標籤頁是否處於焦點狀態以及是否正在使用。這主要用於記錄使用者在應用程式上的非活動時間,並在需要時採取任何措施。
它在其他一些情況下也可能很有用:
如果使用者未正在使用頁面,則阻止傳送網路請求,這將減少伺服器上的流量。
此外,這將有助於節省伺服器成本。
這用於監控每個使用者花費的時間,然後根據這些值計算不同的統計資料。
為了實現此功能,我們有兩種方法,如下所述:
頁面可見性 API
window.onfocus 和 window.onblur 事件
使用頁面可見性 API
可見性 API 由 HTML 5 提供,它可以讓開發者知道標籤當前是否可見。當用戶最小化視窗或將此視窗切換到其他標籤時,API 會發送可見性更改事件。此 API 向 DOM 物件新增以下兩個只能讀取的屬性。
document.hidden − 噹噹前標籤“可見”時,此屬性返回 false,否則返回 true。
document.visibilityState − 此屬性返回一個字串,指示文件當前的可見性狀態。其可能的值為 visible、hidden、prerender 和 unloaded。
示例 1
在下面的示例中,我們正在檢查當用戶切換標籤或最小化視窗時,瀏覽器標籤頁是否處於焦點狀態。
# index.html
<!DOCTYPE html> <html> <head> <title>Page Focus</title> <style> .btn_container { padding: 10px; text-align: center; } #btn { border-radius: 4px; cursor: pointer; padding: 4px 8px; background-color: white; font-size: 1.2em; letter-spacing: 1px; } </style> </head> <body style="text-align: center;"> <h1 style="color:green;">Welcome To Tutorials Point</h1> <h2 id="txt">Switch tab to change the background color.</h2> <div class="btn_container"> <button id="btn">Original Color</button> </div> <script> const ogcolor = "white"; const newcolor = "#C0C0C0"; const txt = document.getElementById("txt"); const btn = document.getElementById("btn"); document.addEventListener("visibilitychange", function (event) { if (document.hidden) { document.body.style.backgroundColor = newcolor; txt.innerText = "Background color has changed !"; } }); btn.addEventListener("click", function () { txt.innerText = "Switch tab to change the background color."; document.body.style.backgroundColor = ogcolor; }); </script> </body> </html>
輸出
使用 window.onfocus 和 window.onblur 事件
window.onfocus − 當標籤獲得焦點時,將觸發此事件。
window.onblur − 當用戶在其他地方執行任何操作時,將觸發 blur 事件。
示例 2
在下面的示例中,我們使用 onFocus 和 onBlur 方法來檢查瀏覽器標籤頁是否處於焦點狀態。
# index.html
<!DOCTYPE html> <html> <head> <title>Page Focus</title> <style> .btn_container { padding: 10px; text-align: center; } #btn { border-radius: 4px; cursor: pointer; padding: 4px 8px; background-color: white; font-size: 1.2em; letter-spacing: 1px; } </style> </head> <body style="text-align: center;"> <h1 style="color:green;">Welcome To Tutorials Point</h1> <h2 id="txt">Switch tab to change the background color.</h2> <div class="btn_container"> <button id="btn">Original Color</button> </div> <script> const ogcolor = "white"; const newcolor = "#C0C0C0"; const txt = document.getElementById("txt"); const btn = document.getElementById("btn"); document.addEventListener("visibilitychange", function (event) { if (document.hidden) { document.body.style.backgroundColor = newcolor; txt.innerText = "Background color has changed !"; } }); btn.addEventListener("click", function () { txt.innerText = "Switch tab to change the background color."; document.body.style.backgroundColor = ogcolor; }); </script> </body> </html>
輸出
廣告