clients/apps/browser/src/platform/offscreen-document/offscreen-document.service.ts
Matt Gibson ee2f96d3c4
Use a service to track when to open and close offscreen document (#8977)
* Use a service to track when to open and close offscreen document

There some strangeness around maintaining the offscreen document for more callbacks, that need not have the same reasons and justifications as the original.

We'd need to test, but perhaps the intent is something closer to maintaining a work queue ourselves and creating the offscreen page for only a single reason as it comes in, then waiting for that page to close before opening another.

* Prefer builtin promise flattening

* Await anything and everything

---------

Co-authored-by: Cesar Gonzalez <cesar.a.gonzalezcs@gmail.com>
2024-05-02 09:10:06 +02:00

42 lines
1012 B
TypeScript

export class DefaultOffscreenDocumentService implements DefaultOffscreenDocumentService {
private workerCount = 0;
constructor() {}
async withDocument<T>(
reasons: chrome.offscreen.Reason[],
justification: string,
callback: () => Promise<T> | T,
): Promise<T> {
this.workerCount++;
try {
if (!(await this.documentExists())) {
await this.create(reasons, justification);
}
return await callback();
} finally {
this.workerCount--;
if (this.workerCount === 0) {
await this.close();
}
}
}
private async create(reasons: chrome.offscreen.Reason[], justification: string): Promise<void> {
await chrome.offscreen.createDocument({
url: "offscreen-document/index.html",
reasons,
justification,
});
}
private async close(): Promise<void> {
await chrome.offscreen.closeDocument();
}
private async documentExists(): Promise<boolean> {
return await chrome.offscreen.hasDocument();
}
}