Skip to content

Commit

Permalink
fix(web): keep app awake after returning from the background (#48)
Browse files Browse the repository at this point in the history
* feat: handle visibility change in web

* chore: format the code
  • Loading branch information
sabereen authored Aug 12, 2024
1 parent 55b23cd commit 39b6e0c
Showing 1 changed file with 14 additions and 0 deletions.
14 changes: 14 additions & 0 deletions src/web.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<void> {
if (!this._isSupported) {
this.throwUnsupportedError();
Expand All @@ -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<void> {
Expand All @@ -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<IsSupportedResult> {
Expand Down

0 comments on commit 39b6e0c

Please sign in to comment.