手机端黑屏时定时器无法执行

最近在写手机端页面时,发现当手机端黑屏时,当前页面的定时器停止执行了。

一开始的思路是,h5也会有想小程序的onShow,onHide的钩子函数的事件可以监听。但是经过各种实验也没能找到这样的事件。

so,开始了解为什么黑屏时定时器停止。经过一系列的百度之后,明白在是ios的为了安全考虑。

You can't. Web pages do not execute javascript unless (1) the page is frontmost and (2) Safari is actually active. Safari does not remain active when the device is asleep.

If you think about it, this functionality would be a massive privacy breach. Imagine how you'd feel if you visited a web page that then secretly tracked your location even when your device was off! You'd be very angry. Even if you could do this technologically, people may be upset if they found out you did it.

Location info is closely guarded for reasons of privacy and physical safety (think about stalkers and your web page.) That is why you get a dialog asking to use the Location Manager the first time you get a location.

既然ios会强行将关闭定时器,于是也找到了方法,用iframe在即使手机被锁定的时候也让js定时执行。

在需要定时器的页面加个iframe

<iframe src="background.html" style="display:none;"></iframe>

iframe代码

<!DOCTYPE HTML>
<head>
<meta http-equiv="refresh" content="3" />
</head>
<body>
<script>
parent.run_function_from_core_page();
</script>
</body>
</html>

这样可以愉快的进行定时任务了

猜你喜欢

转载自www.cnblogs.com/tzzf/p/9123855.html