diff --git a/apps/web/src/app/core/init.service.ts b/apps/web/src/app/core/init.service.ts index 43547ff5d57..dd6cca6c434 100644 --- a/apps/web/src/app/core/init.service.ts +++ b/apps/web/src/app/core/init.service.ts @@ -21,6 +21,7 @@ import { UserAutoUnlockKeyService } from "@bitwarden/common/platform/services/us import { EventUploadService } from "@bitwarden/common/services/event/event-upload.service"; import { KeyService as KeyServiceAbstraction } from "@bitwarden/key-management"; +import { IpcPingService } from "../platform/ipc/ipc-ping.service"; import { VersionService } from "../platform/version.service"; @Injectable() @@ -40,6 +41,7 @@ export class InitService { private accountService: AccountService, private versionService: VersionService, private ipcService: IpcService, + private ipcPingService: IpcPingService, private sdkLoadService: SdkLoadService, private configService: ConfigService, private bulkEncryptService: BulkEncryptService, @@ -75,6 +77,7 @@ export class InitService { this.themingService.applyThemeChangesTo(this.document); this.versionService.applyVersionToWindow(); void this.ipcService.init(); + void this.ipcPingService.init(); const containerService = new ContainerService(this.keyService, this.encryptService); containerService.attachToGlobal(this.win); diff --git a/apps/web/src/app/platform/ipc/ipc-ping.service.ts b/apps/web/src/app/platform/ipc/ipc-ping.service.ts new file mode 100644 index 00000000000..c1fc76edd99 --- /dev/null +++ b/apps/web/src/app/platform/ipc/ipc-ping.service.ts @@ -0,0 +1,43 @@ +import { Injectable } from "@angular/core"; +import { filter, firstValueFrom } from "rxjs"; + +import { IpcService } from "@bitwarden/common/platform/ipc"; +import { Utils } from "@bitwarden/common/platform/misc/utils"; + +/** + * Example service that sends a "ping" message and waits for a "pong" response. + * This is a simple example of how to use the IpcService to send and receive messages. + */ +@Injectable({ providedIn: "root" }) +export class IpcPingService { + constructor(private ipcService: IpcService) {} + + async init() { + // Allow devs to call this function from the browser web console: + // ```js + // await ping(); + // ``` + (window as any).ping = () => this.ping(); + } + + async ping() { + const responsePromise = firstValueFrom( + this.ipcService.messages$.pipe( + filter((m) => Utils.fromBufferToUtf8(new Uint8Array(m.data)) === "pong"), + ), + ); + + // eslint-disable-next-line no-console + console.log("Sending ping..."); + await this.ipcService.send({ + data: Array.from(Utils.fromUtf8ToArray("ping")), + destination: "BrowserBackground", + }); + // eslint-disable-next-line no-console + console.log("Waiting for pong..."); + const response = await responsePromise; + // eslint-disable-next-line no-console + console.log("Received pong:", response); + return response; + } +}