javascript - 如何在浏览器/标签关闭时发送 API 请求?
问题描述
我正在尝试在关闭选项卡/浏览器时发送 API 请求,我尝试过卸载和beforeUnload
处理程序,但它不起作用,我猜测 API 调用没有发生,因为选项卡/浏览器立即关闭,并且没有足够的时间进行请求,在使用调试器关键字进行测试期间一切正常,但并非没有。知道如何在关闭标签/浏览器之前拨打电话吗?
我的代码如下
组件.ts
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
title = 'admin-frontend';
constructor(private loginService: LoginService) {}
ngOnInit() {}
@HostListener('window:unload', ['$event'])
unloadHandler(event) {
if (!!this.loginService.currentUser) {
this.loginService.logout({});
}
}
// вызов логаут когда клиент закрывает браузер или окно
@HostListener('window:beforeunload', ['$event'])
beforeUnloadHandler(event) {
if (!!this.loginService.currentUser) {
this.loginService.logout({});
}
}
}
服务.ts
logout(params) {
return this.post('user/logout', { ...params }, true).subscribe(_ => {
this.applicationId = null;
this.userData.next(null);
this.loginFacade.userData.next(null);
this.storage.clear();
this.user = undefined;
this.router.navigate(['login']);
})
}
核心服务.ts
post<T>(url: string, param: any, withHeader: boolean = false): Observable<T> {
if (withHeader) {
const headers: HttpHeaders = new HttpHeaders({
SessionId: this.user.sessionId,
});
return this.http.post<T>(`${this.apiUrl}/${url}`, param, {
headers: headers,
});
} else {
return this.http.post<T>(`${this.apiUrl}/${url}`, param);
}
}
解决方案
您好,您可以使用此功能检测浏览器关闭
window.onbeforeunload = function () {
return "Do you really want to close?";
};
推荐阅读
- spring-boot - 客户端负载均衡算法
- python - 在python中上传文件
- javascript - 检查是否所有输入字段都填写完毕,然后调用函数js
- python - 您如何在 The Cat API 中按品种召唤猫?
- react-native - 配置项目“:react-native-fast-image”时出现问题
- android - 无重组 [Jetpack Compose]
- python - 给定一个整数列表,找出不能表示为这些数字组合的最小整数(带 +、/ 和 *)
- java - 检查相机中的版本
- arrays - 在 numpy 数组中的第一个元素处添加零或创建数组的方法,将第一个位置保持为零
- vue.js - 如何在 Vue.js 中将文本与附件隔离开来