window.onunload = (e)=>{ _gap_time = new Date().getTime() - _beforeUnload_time; if(_gap_time<=5){ console.log('关闭') navigator.sendBeacon("/manager/api/v1/login/logout",null) } else{ console.log('刷新') navigator.sendBeacon("/manager/api/v1/login/logout",null) } } } window.onbeforeunload = (e)=>{ _beforeUnload_time = new Date().getTime() }
用户关闭或者刷新网页的时候,有时候需要调用后台接口。一般我们通过ajax或者axios等去调用接口。但是在关闭和刷新中调用你会发现console成功但是后台并没有接受到前端的请求,因为调用接口是异步的,很可能在它发送之前,页面已经卸载了,请求并没有发送出去。
浏览器引入的
sendBeacon
方法,发出的是异步请求,但是请求是作为浏览器任务执行的,与当前页面是脱钩的。因此该方法不会阻塞页面卸载流程和延迟后面页面的加载。
监听浏览器关闭/刷新按钮,调用接口
最新推荐文章于 2024-11-04 20:00:23 发布