JavaScript事件为移动浏览器重新启动或唤醒器件重新启动、器件、浏览器、事件

2023-09-05 23:45:18 作者:ambition(野心)

早上好,我正在寻找某种Javascript的事件,我可以用它来检测在移动浏览器窗口重新获得焦点,无论是用户后关闭/最小化他们的浏览器(返回到主屏幕/不同的应用程序) ,或者如果设备从睡眠状态恢复(无论是用户关闭电源,否则会在屏幕超时后睡觉)。

Morning all, I'm looking for some kind of Javascript event I can use to detect when a mobile browser window regains focus, after either a user closes/minimizes their browser (to go back to a home screen/different app), or if the device resumes from sleep (either the user powering it off, or it going to sleep after a screen timeout).

我希望能够找到一个适合所有单个事件,但我知道这是不可能的!该 pageshow 活动适用于iOS设备,但它是只粗略地与一切使用。我试过焦点等待DOMActivate 但他们都不似乎收到预期的效果。

I'd like to be able to find a single event that works for everything, but I know that's unlikely! The pageshow event works for iOS devices, but it's rather sketchy for use with everything else. I've tried focus and DOMActivate but neither of them seem to have the desired effect.

页面可能并不总是有它的表单元素,我真的不希望用户必须再次触摸页面触发事件。

The page may not always have form elements on it, and I don't really want the user to have to touch the page again to trigger the event.

这样的活动要求是由我们的code定期检查通过XHR请求新的内容而引起的。当浏览器是睡着了这些永远不会发送,所以我们从来没有新的内容,重新启动超时。

The requirement for such an event is caused by our code periodically checking for new content by making XHR requests. These are never sent when the browser is asleep, so we never get new content to restart the timeouts.

感谢您的帮助,你们也许能提供!

Thanks for any help you guys may be able to provide!

推荐答案

我们也有类似的问题,解决了这个问题是这样的:

We had a similar issue and solved it something like this:

var lastSync = 0;
var syncInterval = 60000; //sync every minute

function syncPage() {
  lastSync = new Date().getTime(); //set last sync to be now
  updatePage(); //do your stuff
}

setInterval(function() {
  var now = new Date().getTime();
  if ((now - lastSync) > syncInterval ) {
    syncPage();
  }
}, 5000); //check every 5 seconds whether a minute has passed since last sync

这样,您将同步每一分钟,如果你的网页是活动的,如果你把你的浏览器在空闲模式下的一分多钟,在5秒内传递,然后在再次打开浏览器同步。短的时间间隔可能会消耗电池的比你多想,所以适应计时时,你需要记住这一点。

This way you would sync every minute if your page is active, and if you put your browser in idle mode for over a minute, at most 5 seconds will pass before you sync upon opening the browser again. Short intervals might drain the battery more than you would like, so keep that in mind when adapting the timings to you needs.