From c836f2f2acc29bf0062268a0f6579904db188465 Mon Sep 17 00:00:00 2001 From: Niranjana Binoy <43930900+NiranjanaBinoy@users.noreply.github.com> Date: Fri, 23 Sep 2022 20:39:25 -0400 Subject: [PATCH] Replacing setTimeout in auto-lock time limit with chrome alarm (#15931) --- app/manifest/v3/_base.json | 1 + app/scripts/controllers/app-state.js | 35 ++++++++++++++++++++++++---- shared/constants/alarms.js | 1 + 3 files changed, 32 insertions(+), 5 deletions(-) create mode 100644 shared/constants/alarms.js diff --git a/app/manifest/v3/_base.json b/app/manifest/v3/_base.json index 696a4d62e..1b9456fd8 100644 --- a/app/manifest/v3/_base.json +++ b/app/manifest/v3/_base.json @@ -67,6 +67,7 @@ "name": "__MSG_appName__", "permissions": [ "activeTab", + "alarms", "clipboardWrite", "notifications", "scripting", diff --git a/app/scripts/controllers/app-state.js b/app/scripts/controllers/app-state.js index 5dfdc2f70..76eab8367 100644 --- a/app/scripts/controllers/app-state.js +++ b/app/scripts/controllers/app-state.js @@ -2,6 +2,8 @@ import EventEmitter from 'events'; import { ObservableStore } from '@metamask/obs-store'; import { METAMASK_CONTROLLER_EVENTS } from '../metamask-controller'; import { MINUTE } from '../../../shared/constants/time'; +import { AUTO_LOCK_TIMEOUT_ALARM } from '../../../shared/constants/alarms'; +import { isManifestV3 } from '../../../shared/modules/mv3.utils'; export default class AppStateController extends EventEmitter { /** @@ -187,21 +189,44 @@ export default class AppStateController extends EventEmitter { * * @private */ + /* eslint-disable no-undef */ _resetTimer() { const { timeoutMinutes } = this.store.getState(); if (this.timer) { - clearTimeout(this.timer); + if (isManifestV3) { + chrome.alarms.clear(AUTO_LOCK_TIMEOUT_ALARM); + } else { + clearTimeout(this.timer); + } } if (!timeoutMinutes) { return; } - this.timer = setTimeout( - () => this.onInactiveTimeout(), - timeoutMinutes * MINUTE, - ); + if (isManifestV3) { + chrome.alarms.create(AUTO_LOCK_TIMEOUT_ALARM, { + delayInMinutes: timeoutMinutes, + periodInMinutes: timeoutMinutes, + }); + chrome.alarms.onAlarm.addListener(() => { + chrome.alarms.getAll((alarms) => { + const hasAlarm = alarms.find( + (alarm) => alarm.name === AUTO_LOCK_TIMEOUT_ALARM, + ); + if (hasAlarm) { + this.onInactiveTimeout(); + chrome.alarms.clear(AUTO_LOCK_TIMEOUT_ALARM); + } + }); + }); + } else { + this.timer = setTimeout( + () => this.onInactiveTimeout(), + timeoutMinutes * MINUTE, + ); + } } /** diff --git a/shared/constants/alarms.js b/shared/constants/alarms.js new file mode 100644 index 000000000..c0dbbcf7e --- /dev/null +++ b/shared/constants/alarms.js @@ -0,0 +1 @@ +export const AUTO_LOCK_TIMEOUT_ALARM = 'AUTO_LOCK_TIMEOUT_ALARM';