how to using js detect browser window tab close event All In One
how to using js detect browser window tab close event All In One
JavaScript 中的一些加载,
卸载
事件:
- 页面
加载
时只执行 onload
事件; - 页面
关闭
时,先 onbeforeunload
事件,再 onunload
事件; - 页面
刷新
时先执行 onbeforeunload
事件,然后 onunload
事件,最后 onload
事件;
window.addEventListener('load', (event) => {
console.log('page is fully loaded');
});
window.addEventListener('DOMContentLoaded', (event) => {
console.log('DOM fully loaded and parsed');
});
demos
// tab
window.addEventListener('beforeunload', () => {
const params = {
user: this.username ?? '',
group: this.group ?? '',
modules: '',
path: '',
host: window.location.host,
os: this.os,
desc: 'tab 关闭✅',
};
params.modules = newPageName ?? '';
params.path = newPathname;
wxRobot(params, 'tab 关闭', true);
// setTimeout(() => {
// window.removeEventListener('beforeunload');
// }, 0);
});
const wxRobot = (params = {}, desc = '', clearEvent = false) => {
// 企业微信-robot
// const url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=xxxyyyzzz';
const fetchPOST = (url, obj) => {
return fetch(
url,
{
method: 'POST',
mode: 'no-cors',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(obj),
},
).then(res => res.json()).then(json => json).catch(err => console.log('fetch error', err)).finally(() => {
if(clearEvent) {
window.removeEventListener('beforeunload');
}
});
};
const obj = {
msgtype: 'markdown',
markdown: {
content: `
> tab 关闭 App 数据上报\n
desciption: ${desc}\n
data: ${JSON.stringify(params, null, 4)}\n
`,
},
};
fetchPOST(url, obj);
};
// wxRobot(params, desc);
Web API
MDN
addEventListener('pageshow', (event) => { });
onpageshow = (event) => { };
https://developer.mozilla.org/en-US/docs/Web/API/Window/pageshow_event
addEventListener('pagehide', (event) => { });
onpagehide = (event) => { };
https://developer.mozilla.org/en-US/docs/Web/API/Window/pagehide_event
addEventListener('DOMContentLoaded', (event) => {});
onDOMContentLoaded = (event) => { };
https://developer.mozilla.org/en-US/docs/Web/API/Window/DOMContentLoaded_event
addEventListener("load", (event) => {});
onload = (event) => {};
https://developer.mozilla.org/en-US/docs/Web/API/Window/load_event
addEventListener('beforeunload', (event) => { });
onbeforeunload = (event) => { };
https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event
addEventListener('unload', (event) => { });
onunload = (event) => { };
https://developer.mozilla.org/en-US/docs/Web/API/Window/unload_event
潜在 bug 问题❌
https://developer.mozilla.org/en-US/docs/Web/API/Window/unload_event#usage_notes
refs
https://juejin.cn/post/6844903871668551687
https://segmentfault.com/a/1190000016874879
(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!
©xgqfrms 2012-2021
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/14627068.html
未经授权禁止转载,违者必究!