我需要在操作系统休眠/睡眠之前执行一个函数,以优雅地关闭WebRTC连接。在浏览器中有没有事件侦听器或某种方法可以检测到这一点?
我已经尝试过"beforeunload",但它不能捕获到它。
我需要在操作系统休眠/睡眠之前执行一个函数,以优雅地关闭WebRTC连接。在浏览器中有没有事件侦听器或某种方法可以检测到这一点?
我已经尝试过"beforeunload",但它不能捕获到它。
有一个草案冻结事件
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>