gpt4 book ai didi

javascript - 如何在 iOS/Android 上的浏览​​器中检测从 sleep 中唤醒?

转载 作者:行者123 更新时间:2023-11-28 21:44:11 25 4
gpt4 key购买 nike

我希望能够在用户从不同的选项卡或通过唤醒设备返回页面时刷新页面。

我本可以发誓我在某处读到 pageshow 事件会从窗口触发,但事实并非如此。

window.onfocus 似乎可以解决问题,但我想确认这是否可靠,或者是否有更合适的方法。

最佳答案

事实证明,正确的答案是从文档中监听 visibilitychange 事件,然后测试文档中的 hidden 属性。

来自 MDN :

// Set the name of the hidden property and the change event for visibility
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";
}

var videoElement = document.getElementById("videoElement");

// If the page is hidden, pause the video;
// if the page is shown, play the video
function handleVisibilityChange() {
if (document[hidden]) {
videoElement.pause();
} else {
videoElement.play();
}
}

// Warn if the browser doesn't support addEventListener or the Page Visibility API
if (typeof document.addEventListener === "undefined" ||
typeof document[hidden] === "undefined") {
alert("This demo requires a browser, such as Google Chrome or Firefox, that supports the Page Visibility API.");
} else {
// Handle page visibility change
document.addEventListener(visibilityChange, handleVisibilityChange, false);

// Revert to the existing favicon for the site when the page is closed;
// otherwise the favicon remains paused.png
window.addEventListener("unload", function(){
favicon.change("/favicon.ico");
}, false);

// When the video pauses, set the favicon.
// This shows the paused.png image
videoElement.addEventListener("pause", function(){
favicon.change("images/paused.png");
}, false);

// When the video plays, set the favicon.
videoElement.addEventListener("play", function(){
favicon.change("images/playing.png");
}, false);

// set the document (tab) title from the current video time
videoElement.addEventListener("timeupdate", function(){
document.title = Math.floor(videoElement.currentTime) + " second(s)";
}, false);
}

关于javascript - 如何在 iOS/Android 上的浏览​​器中检测从 sleep 中唤醒?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30933244/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com