Angular 2 - Execute code when closing window
Asked Answered
T

3

38

I am working on a chat application using angular 2.

How can i send the finish chat command to the backend when the user closes the window?

My component has a method that calls the backend service to end the chat in the following way

 endChat() {
        this.chatService.endChat(this.chatSessionInfo).subscribe(
            result => this.OnGetMessages(result),
            error => this.OnChatEndError(error)
        );
    }

How can i execute that code when closing the window? How can i detect the window close event?

I tried with ngOnDestroy but for some reason the code is not being executed.

In my Component.ts I have.

import { Component, OnInit, AfterViewChecked, ElementRef, ViewChild,OnDestroy} from '@angular/core';

export class ChatComponent implements OnInit, AfterViewChecked,OnDestroy  {

and finally

 ngOnDestroy() { 
    this.endChat();
 }

Thanks!

Tobe answered 17/8, 2016 at 14:46 Comment(6)
Have you implemented the backend with socket.io?Catatonia
No, i am using WebApi 2Tobe
I don't know how you wired up your chat in the background, but I'd suggest using SignalR for something like a chat. On disconnect there will be fired an event on the server. Have a look here for an example: github.com/FabianGosebrink/…Catatonia
use jquery for that check this answer #1632459Reine
@rinukkusu I am using socket.io. Do you have a socket.io specific solution for this?Buccinator
@MarcBorni No, I'd go with Günter's answer! BUT if you just need to execute some code on your backend, then there is the 'disconnect' event.Catatonia
T
68

Thanks everyone for the help. I was able to create a solution based on different proposal.

First I used the beforeunload event in the component

@HostListener('window:beforeunload', ['$event'])
beforeunloadHandler(event) {
    this.endChat();
}

where

endChat() {
    this.chatService.endChatSync(this.chatSessionInfo);
}

Then, the trick is to make the http call sync not async.

Before, the endchat method at the chat service was

    endChat(chatSessionInfo: ChatSessionInfo)  : Observable<ChatTranscription> {
    console.log("Ending chat..");
    let body = JSON.stringify(chatSessionInfo);
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });
    return this.http.delete(this.apiUrl + "Chat?userId="+chatSessionInfo.UserId+"&secureKey="+chatSessionInfo.SecureKey,options)
             .map(this.extractData)
            .catch(this.handleError);
}

I was able to make it work with

endChatSync(chatSessionInfo: ChatSessionInfo)  {
    console.log("Ending chat..");
     let xhr = new XMLHttpRequest()
     xhr.open("DELETE",this.apiUrl +"Chat?userId="+chatSessionInfo.UserId+"&secureKey="+chatSessionInfo.SecureKey,false);
     xhr.send();
}

Hope this helps!

Tobe answered 17/8, 2016 at 20:42 Comment(1)
Have you tested new XMLHttpRequest() in all browsers?Ribonuclease
L
23
@HostListener('window:unload', ['$event'])
unloadHandler(event) {
  ...
}

See also javascript to check when the browser window is close

Longfaced answered 17/8, 2016 at 15:18 Comment(9)
Does this have a timeout or does it block until the handler finishes?Catatonia
See developer.mozilla.org/de/docs/Web/API/WindowEventHandlers/…, developer.mozilla.org/de/docs/Web/Events/beforeunload. I haven't used them myself for a while and don't remember details.Shortcircuit
The issue in that case is that the window get closed before the service call is sent..Tobe
I know thos is tricky but there is nothing Angular can do about it. That's a browser limitation.Shortcircuit
@GünterZöchbauer Where should i have to write this code?Prisca
@HostListener('window:unload', ['$event']) didn't work for me (Angular2 v2.4.6) to show the confirmation dialog by setting the e.returnValue. What did was @HostListener('window:beforeunload', ['$event']), however.Went
Take a look at my previous post. That works for Angular 2Tobe
@GünterZöchbauer could you help me to solve this #50267474Minneapolis
I used unloadHandler and beforeUnloadHandler.. sometimes it does logging and sometimes it misses it.. I need log everytime when app is closed...Peonir
S
3

Chrome now disallows synchronous XHR during page dismissal when the page is being navigated away from or closed by the user.

https://www.chromestatus.com/feature/4664843055398912

so now what to do to make synchronous calls on this event.

Sleeper answered 4/3, 2020 at 11:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.