From 39b6e0cf0c186210f0022d4a7bcb2fe6e2ba01e6 Mon Sep 17 00:00:00 2001 From: Mojtaba Ghasemzadeh Tehrany Date: Tue, 13 Aug 2024 01:53:14 +0330 Subject: [PATCH] fix(web): keep app awake after returning from the background (#48) * feat: handle visibility change in web * chore: format the code --- src/web.ts | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/src/web.ts b/src/web.ts index 9afe681..df03e11 100644 --- a/src/web.ts +++ b/src/web.ts @@ -11,6 +11,10 @@ export class KeepAwakeWeb extends WebPlugin implements KeepAwakePlugin { private readonly _isSupported = typeof navigator !== 'undefined' && 'wakeLock' in navigator; + private handleVisibilityChange = () => { + if (document.visibilityState === 'visible') this.keepAwake(); + }; + public async keepAwake(): Promise { if (!this._isSupported) { this.throwUnsupportedError(); @@ -19,6 +23,8 @@ export class KeepAwakeWeb extends WebPlugin implements KeepAwakePlugin { await this.allowSleep(); } this.wakeLock = await navigator.wakeLock.request('screen'); + document.addEventListener('visibilitychange', this.handleVisibilityChange); + document.addEventListener('fullscreenchange', this.handleVisibilityChange); } public async allowSleep(): Promise { @@ -27,6 +33,14 @@ export class KeepAwakeWeb extends WebPlugin implements KeepAwakePlugin { } this.wakeLock?.release(); this.wakeLock = null; + document.removeEventListener( + 'visibilitychange', + this.handleVisibilityChange, + ); + document.removeEventListener( + 'fullscreenchange', + this.handleVisibilityChange, + ); } public async isSupported(): Promise {