简体   繁体   English

如何在浏览器/选项卡关闭时发送 API 请求?

[英]How to send API request on browser/tab close?

I am trying to send API request while closing tab/browser, I have tried unload and beforeUnload handler, but It does not work, I am guessing that API call not occurring because tab/browser closes instantly, and there isn't enough time to make request, everything is working during testing with debugger keyword, but doesn't without.我试图在关闭选项卡/浏览器时发送 API 请求,我尝试了卸载和beforeUnload处理程序,但它不起作用,我猜 API 调用不会发生,因为选项卡/浏览器立即关闭,并且没有足够的时间来发出请求,在使用 debugger 关键字进行测试期间一切正常,但并非没有。 Any Idea how can I make a call before closing tab/browser?知道如何在关闭标签/浏览器之前拨打电话吗?

My code below我的代码如下

component.ts组件.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({});
    }
  }
}

service.ts服务.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']);
        })
    }

core.service.ts核心服务.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);
    }
  }

Hi you can use this function to detect browser close嗨,您可以使用此 function 来检测浏览器关闭

window.onbeforeunload = function () {
    return "Do you really want to close?";
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM