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

后端 未结 4 801
暖寄归人
暖寄归人 2020-12-03 17:06

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

4条回答
  •  暖寄归人
    2020-12-03 17:57

    Found a nice function here:

    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 resume event.

提交回复
热议问题