HTML 5 Page Visibility- 判斷網頁是否可視
Page Visibility是html 5新的API,可以判斷現在是不是可見狀態,如果切換到別的tab或把瀏覽器縮到最小,就可以偵測並觸發事件。一般用在js必須要不斷執行的地方,比如說time interval,或是video的播放,當使用者沒有在當前頁面,可以節省資源的浪費。
首先判斷瀏覽器
- var hidden, visibilityChange;
- if (typeof document.hidden !== "undefined") { // Opera 12.10 and Firefox 18 and later support
- hidden = "hidden";
- visibilityChange = "visibilitychange";
- } else if (typeof document.mozHidden !== "undefined") {
- hidden = "mozHidden";
- visibilityChange = "mozvisibilitychange";
- } else if (typeof document.msHidden !== "undefined") {
- hidden = "msHidden";
- visibilityChange = "msvisibilitychange";
- } else if (typeof document.webkitHidden !== "undefined") {
- hidden = "webkitHidden";
- visibilityChange = "webkitvisibilitychange";
- }
然後寫判斷是否hidden,播放或暫停影片
- var videoElement = document.getElementById("myvideo");
- // 如果hidden, 暫停影片;
- // 如果出現, 播放影片
- function handleVisibilityChange() {
- if (document[hidden]) {
- videoElement.pause();
- } else {
- videoElement.play();
- }
- }
最後在加這段就大功告成了
- if (typeof document.addEventListener === "undefined" ||
- typeof hidden === "undefined") {
- alert("您的瀏覽器需要支援 Page Visibility API.");
- } else {
- // 偵測page visibility事件
- document.addEventListener(visibilityChange, handleVisibilityChange, false);
- // 改變web page title 名稱
- videoElement.addEventListener("timeupdate", function(){
- document.title = Math.floor(videoElement.currentTime) + " second(s)";
- }, false);
- }
Demo
Page Visibility
參考
W3C Page Visibility
Using the PageVisibility API
Using the Page Visibility API
留言