问题
I'm currently trying to make an Angular app make an API service call when the user tries to navigate away from my page. Either by closing the tab / window, or typing in an external URL.
I've tried to implement several different ways I've seen described here on stackoverflow questions, but none seem to have the desired effect. Some mention sync ajax requests which have been, or are in the process of being deprecated in onbeforeunload on Chrome. Others advise the use of XMLHttpRequests, which seem to have suffered the same fate.
I have attempted the use of
@HostListener('window:onbeforeunload', ['$event'])
, and equivalent in the HTML (window:beforeunload)="doBeforeUnload($event)"
, but all refuse to cooperate. I can get console.logs to show up, but the API never receives any call to logout the user.
I have also used navigator.sendBeacon
and, despite its function returning true, signalling that the job was sent to the browser queue, nothing ever materializes.
Currently, the logout function is this:
userLogout(): Observable<any> {
return this.apiService.get('/Account/Logout/');
}
Which, in turn, is a generic http get function:
get<T>(url: string, options?: { params: HttpParams }): Observable<any> {
return this.httpRequest<T>('get', url, null, options ? options.params : null);
}
The full url is added with the use of an HttpInterceptor. The logout function itself is working, as it is used in a menu option that works as expected when used manually. So the function should not be the problem.
All I'm attempting to do is to call the userLogout function either in a sync or async way and inform the backend that the user has left.
回答1:
After some tinkering, I ended up with a solution based on this answer, even though, for some reason, it didn't work for me on my first attempts.
I added the following HostBinding to the component:
@HostListener('window:beforeunload', ['$event']) beforeunloadHandler(event) {
this.pageClosed();
}
Which calls a simple function that will use the authentication service logout method.
pageClosed() {
this.authenticationService.userLogoutSync();
}
I had to create a separate logout function, so that it could be synchronous. Headers also had to be added for backend authorization, as my Http interceptor was unable to catch the XMLHttpRequest and add them itself.
const xhr = new XMLHttpRequest();
xhr.open('GET', environment.backend + '/Account/Logout/', false);
xhr.setRequestHeader('Authorization', 'Bearer ' + this.jwtService.getAccessToken());
xhr.send();
}
来源:https://stackoverflow.com/questions/56113875/perform-an-asynchronous-service-get-when-closing-browser-window-tab-with-angul