是否可以在 JavaScript 中检测 Android 和 iOS 浏览器中的屏幕何时关闭

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15959244/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 02:45:01  来源:igfitidea点击:

Is it possible, in JavaScript, to detect when the screen is turned off in the Android & iOS browsers

javascriptandroidiosmobile-safariandroid-browser

提问by Nathan Friedly

I was tracking down some ridiculously high load times that my app's javascript reported, and found that Android (and iOS) pause some JavaScript execution when the window is in the background or the display is off.

我正在跟踪我的应用程序的 javascript 报告的一些高得离谱的加载时间,并发现当窗口处于后台或显示器关闭时,Android(和 iOS)会暂停一些 JavaScript 执行。

On Android, I found that I could use the window.onfocusand onblurevents to detect when the app was switching to the background (and js execution would soon be paused, at least for new scripts), but I can't find a way to detect when the screen is turned on or off. Is this possible?

在 Android 上,我发现我可以使用window.onfocusonblur事件来检测应用程序何时切换到后台(并且 js 执行很快就会暂停,至少对于新脚本而言),但是我找不到一种方法来检测何时屏幕打开或关闭。这可能吗?

(On Safari, I had similar results except that onfocusand onblurdidn't fire reliably.)

(在 Safari 上,我得到了类似的结果,除此之外onfocusonblur没有可靠地触发。)

采纳答案by Dmytro Medvid

There is few options to check it:

有几个选项可以检查它:

  1. Using Visibility API

  2. Using focusand blurevents to detect browser tab visibility:

  1. 使用可见性 API

  2. 使用focusblur事件来检测浏览器选项卡的可见性:

window.addEventListener("focus", handleBrowserState.bind(context, true));
window.addEventListener("blur", handleBrowserState.bind(context, false));

function handleBrowserState(isActive){
    // do something
}
  1. Using timers, as mentioned above
  1. 使用计时器,如上所述

回答by Nathan Friedly

I just found a pretty good solution for my use case:

我刚刚为我的用例找到了一个很好的解决方案:

function getTime() {
    return (new Date()).getTime();
}

var lastInterval = getTime();

function intervalHeartbeat() {
    var now = getTime();
    var diff = now - lastInterval;
    var offBy = diff - 1000; // 1000 = the 1 second delay I was expecting
    lastInterval = now;

    if(offBy > 100) { // don't trigger on small stutters less than 100ms
        console.log('interval heartbeat - off by ' + offBy + 'ms');
    }
}

setInterval(intervalHeartbeat, 1000);

When the screen is turned off (or JS is paused for any reason), the next interval is delayed until JS execution resumes. In my code, I can just adjust the timers by the offByamount and call it good.

当屏幕关闭(或 JS 因任何原因暂停)时,下一个间隔会延迟,直到 JS 执行恢复。在我的代码中,我可以按offBy数量调整计时器并称其为好。

In quick testing, this seemed to work well on both Android 4.2.2's browser and Safari on iOS 6.1.3.

在快速测试中,这似乎在 Android 4.2.2 的浏览器和 iOS 6.1.3 上的 Safari 上运行良好。

回答by Dunc

Found a nice function here:

在这里找到了一个不错的功能:

http://rakaz.nl/2009/09/iphone-webapps-101-detecting-essential-information-about-your-iphone.html

http://rakaz.nl/2009/09/iphone-webapps-101-detecting-essential-information-about-your-iphone.html

(function() {
    var timestamp = new Date().getTime();

    function checkResume() {
        var current = new Date().getTime();
        if (current - timestamp > 4000) {
            var event = document.createEvent("Events");
            event.initEvent("resume", true, true);
            document.dispatchEvent(event);
        }
        timestamp = current;
    }

    window.setInterval(checkResume, 1000);
})();   

To register for event:

注册活动:

addEventListener("resume", function() {
    alert('Resuming this webapp');
});

This is consistent with Cordova which also fires the resumeevent.

这与也触发resume事件的Cordova 一致。

回答by comeGetSome

what will you do in your script once you now that the screen turns off? Well anyway, you can inject Java objects ( http://developer.android.com/reference/android/webkit/WebView.html#addJavascriptInterface(java.lang.Object,%20java.lang.String)) to interface with the activity and proxy all information you require in JS world.

屏幕关闭后,您将在脚本中做什么?无论如何,您可以注入 Java 对象(http://developer.android.com/reference/android/webkit/WebView.html#addJavascriptInterface(java.lang.Object,%20java.lang.String))与活动交互并代理您在 JS 世界中需要的所有信息。