如何检测浏览器未最小化和相关选项卡不活动

时间:2015-09-26 11:23:43

标签: javascript html browser

在我的网站上,有一个下载页面。我想在下载页面等待我的用户15秒。我想在下载按钮出现之前添加15秒计时器。意思是如果用户在浏览器中单击另一个选项卡或最小化浏览器,则计时器应该停止。

我的问题是如何检测用户是否继续在网页上观看,这意味着浏览器未最小化,此选项卡未处于非活动状态。如何在javascript中执行此任务。

1 个答案:

答案 0 :(得分:1)

这里是一个随时可用的js

(function() {
    var hidden, visibilityChange;
    if (typeof document.hidden !== "undefined") { 
        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";
    }


    // If the page is hidden, pause the countdown;
    // if the page is shown, resume the countdown
    function handleVisibilityChange() {
        if (document[hidden]) {

            //pause your countdown
        } else {

            //resume your countdown
        }
    }

    // Warn if the browser doesn't support addEventListener or the Page Visibility API
    if (typeof document.addEventListener === "undefined" ||
        typeof document[hidden] === "undefined") {} else {
        // Handle page visibility change   
        document.addEventListener(visibilityChange, handleVisibilityChange, false);

    }
})();

希望这可以帮到你! :)