官方介绍:https://developer.mozilla.org/zh-CN/docs/Web/API/Navigator/sendBeacon
可参考:https://www.jianshu.com/p/04e88271a8f2?from
终极解决方案:
window.addEventListener("beforeunload", (e) => {
const data = {name: "tm"};
window.navigator.sendBeacon("http://127.0.0.1:1891/loginout", JSON.stringify(data));
});
不管是刷新页面还是关闭页面,后台都能接收到前端发送过来的请求,完美实现需求。