You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

移动端屏幕锁定时JavaScript代码停止运行,如何解决?

移动端锁屏时暂停JavaScript代码运行的解决方案

嘿,我给你调整了代码,用浏览器的Page Visibility API就能搞定锁屏时停止代码运行的需求——这个API可以检测页面是否处于可见状态,当用户锁定屏幕或者把App切到后台时,页面会变成不可见,我们就可以暂停Firebase监听和相关逻辑,解锁后再恢复,避免后台无效运行消耗资源。

下面是修改后的完整代码,我加了详细注释:

// 初始化Firebase
firebase.initializeApp(config);

// 处理通知权限请求
if (!window.Notification) {
  alert('浏览器不支持通知功能');
} else {
  Notification.requestPermission().then(function(p) {
    if (p === 'denied') {
      alert('你拒绝了通知权限');
    } else if (p === 'granted') {
      alert('你允许了通知权限');
    }
  });
}

// 声明变量保存Firebase监听引用,方便后续移除
let motionListener = null;
const databaseRef = firebase.database().ref("sensor/Motion");

// 定义监听Motion变化的逻辑函数
function startMotionListening() {
  motionListener = databaseRef.on('child_added', function() {
    $("#Mt").val("Motion detected");
    $("#dateM").val(moment().format('LLL'));
    
    // 补全你原来未完成的通知触发逻辑
    if (Notification.permission === 'granted') {
      new Notification('Motion Alert', {
        body: '检测到运动!',
        icon: '你的图标路径(可选)'
      });
    }
  });
}

// 定义停止监听的函数
function stopMotionListening() {
  if (motionListener) {
    databaseRef.off('child_added', motionListener);
    motionListener = null;
  }
}

// 监听页面可见状态变化(锁屏/切后台会触发)
document.addEventListener('visibilitychange', function() {
  if (document.visibilityState === 'hidden') {
    // 页面不可见时,停止Firebase监听
    stopMotionListening();
    console.log('页面已隐藏,暂停Motion监听');
  } else {
    // 页面可见时,恢复监听
    startMotionListening();
    console.log('页面已显示,恢复Motion监听');
  }
});

// 页面加载完成后,默认启动监听
startMotionListening();

关键说明:

  • Page Visibility API:通过document.visibilityState判断页面状态,hidden表示页面不可见(锁屏、切后台、最小化等),visible表示页面可见。
  • Firebase监听的管理:把on('child_added')的返回值保存起来,用off()方法可以精准移除对应的监听,避免内存泄漏。
  • 通知逻辑补全:我帮你补全了原来未写完的通知触发代码,确保只有在权限允许时才弹出通知。

内容的提问来源于stack exchange,提问作者Nouali Ibrahim Yassine

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:41:20