浏览器如何检测操作系统何时将进入休眠/睡眠状态

4

我需要在操作系统休眠/睡眠之前执行一个函数,以优雅地关闭WebRTC连接。在浏览器中有没有事件侦听器或某种方法可以检测到这一点?

我已经尝试过"beforeunload",但它不能捕获到它。

1个回答

3

有一个草案冻结事件

https://wicg.github.io/page-lifecycle/spec.html

但是目前回答时,它并没有被广泛或可靠地支持。

https://caniuse.com/mdn-api_document_freeze_event

如果您想要冻结事件的实现,您可以在https://whatwebcando.today/freeze-resume.html中找到它。

API glimpse

document.addEventListener('freeze')  

An event fired when the page has been frozen and unloaded by the operating system.

document.addEventListener('resume')  

An event fired when the page has been resumed after being frozen by the operating system.

 document.wasDiscarded

A boolean flag indicating whether the current load has happened after the web application has been previously discarded.

来自该页面的相关代码片段。

var target = document.getElementById('target');

if ('wasDiscarded' in document) {
  document.getElementById('wasDiscarded').innerText = document.wasDiscarded.toString();
}

function getState() {
  if (document.visibilityState === 'hidden') {
    return 'hidden';
  }
  if (document.hasFocus()) {
    return 'focused';
  }
  return 'not focused';
};

var state = getState();

function logStateChange(nextState) {
  var prevState = state;
  if (nextState !== prevState) {
    var timeBadge = new Date().toTimeString().split(' ')[0];
    var newLog = document.createElement('p');
    newLog.innerHTML = '' + timeBadge + ' State changed from ' + prevState + ' to ' + nextState + '.';
    target.appendChild(newLog);
    state = nextState;
  }
};

function onPageStateChange() {
  logStateChange(getState())
}

['pageshow', 'focus', 'blur', 'visibilitychange', 'resume'].forEach(function (type) {
  window.addEventListener(type, onPageStateChange, {capture: true});
});

function onFreeze() {
  logStateChange('frozen');
}

window.addEventListener('freeze', onFreeze, {capture: true});

function onPageHide(event) {
  if (event.persisted) {
    // If the event's persisted property is `true` the page is about
    // to enter the page navigation cache, which is also in the frozen state.
    logStateChange('frozen');
  } else {
    // If the event's persisted property is not `true` the page is about to be unloaded.
    logStateChange('terminated');
  }
}

window.addEventListener('pagehide', onPageHide, {capture: true});
<p>Was current page load initiated from a discarded state? 
  <b id="wasDiscarded">unknown</b>.</p>
  <p>Change the browser tab state to observe the changes log.</p>
<div id="target"></div>
<p><small>Based on the demo from <a href="https://developers.google.com/web/updates/2018/07/page-lifecycle-api" target="_blank" rel="noopener">Google Developers</a>.</small></p>


这很有帮助,但并不能完全解决问题。它会在操作系统即将进入休眠/睡眠状态时触发,但也会在您切换选项卡时触发。我只需要在操作系统进入睡眠状态的情况下触发。 - user1591482
@user1591482 不过这已经是你能得到的最好的了。浏览器非常谨慎,不会随意向随机的JavaScript提供裸露的访问权限。 - Tschallacka

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接