javascript - 瀏覽器如何檢測作業系統即將進入休眠/睡眠
我必須在作業系統進入休眠/睡眠模式之前執行一個函數,以優雅地關閉 webrtc 連線。瀏覽器中有事件監聽器或特定方式可以偵測到這個情況嗎?
我嘗試過使用「beforeunload」,但它無法捕捉到。
答案#1
有一個草稿凍結事件
https://wicg.github.io/page-lifecycle/spec.html
但在回答時刻尚未被廣泛或可靠地支持
https://caniuse.com/mdn-api_document_freeze_event
如果你想要一個 freeze 事件的實現,你可以在 https://whatwebcando.today/freeze-resume.html 找到它
API 一瞥
document.addEventListener('freeze')當頁面被操作系統凍結並卸載時觸發的事件。
document.addEventListener('resume')當頁面在被作業系統凍結後恢復時觸發的事件。
document.wasDiscarded一個布林標誌,用於指示當前載入是否發生在網頁應用程序先前已被丟棄之後。
來自該頁面的相關程式碼片段。
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>.</p>