Beacon API & Page Visibility API & pagehide & Front-End Monitor In Action
Beacon API & Page Visibility API & pagehide & Front-End Monitor In Action
close tab
client
const log = console.log;
log('app init');
const monitorLog = (obj = {}, text = '') => {
// Test that we have support
if (!navigator.sendBeacon) {
// XHR fallback
const url = 'http://localhost:3000/api/post';
this.loading = true;
fetch(url, {
headers: {
"Content-Type": "application/json",
},
method: "POST",
// mode: "no-cors",
mode: "cors",
cache: "no-cache",
body: JSON.stringify(obj),
})
.then(res => console.log(`res =`, res))
.catch(err => console.error(`error =`, err))
.finally(() => {
this.loading = false;
});
// return true;
} else {
const url = 'http://localhost:3000/api/beacon';
// Content-Type: application/x-www-form-urlencoded
// const data = new FormData();
// const keys = Object.keys(obj);
// for (const key of keys) {
// data.append(key, obj[key]);
// }
// if(text) {
// data.append('desc', text);
// }
// console.log(`Beacon API 🔥 数据上报 = ${JSON.stringify(obj, null, 4)}`);
const data = new Blob(
[JSON.stringify(obj)],
{type : 'application/json'}
);
navigator.sendBeacon(url, data);
}
};
server
app.post('/api/post', (req, res) => {
console.log('\npost req.body =', req.body);
// console.log('post req', req);
// console.log('post req', req.params, req.query);
res.setHeader('Content-Type', 'application/json');
// res.sendStatus(200);
res.send({res: 'post api'});
});
app.post('/api/beacon', (req, res) => {
console.log('\nbeacon req.body =', req.body);
// console.log('beacon req', req);
// console.log('beacon', req.params, req.query);
res.setHeader('Content-Type', 'application/json');
// res.sendStatus(200);
res.send({res: 'beacon api'});
});
demo
steps
-
run the express server
-
open the URL
http://localhost:3000/
-
close the tab
-
check the logs
refs
https://developer.mozilla.org/en-US/docs/Web/API/Beacon_API
https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API
https://developer.mozilla.org/en-US/docs/Web/API/Window/pagehide_event
page-lifecycle-api
https://github.com/GoogleChromeLabs/page-lifecycle
https://developers.google.com/web/updates/images/2018/07/page-lifecycle-api-state-event-flow.png
Back/forward cache
window.addEventListener('pagehide', function(event) {
if (event.persisted === true) {
console.log('This page *might* be entering the bfcache.');
} else {
console.log('This page will unload normally and be discarded.');
}
});
©xgqfrms 2012-2020
www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/14707234.html
未经授权禁止转载,违者必究!