-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbackground.js
More file actions
1607 lines (1476 loc) · 63.9 KB
/
Copy pathbackground.js
File metadata and controls
1607 lines (1476 loc) · 63.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// background service worker
// all listeners at top level for MV3
const DEFAULT_SETTINGS = {
suspendAfterMinutes: 15,
whitelist: [],
enableAutoSuspend: true,
protectPinned: true,
protectAudio: true,
protectForms: false,
suspendOnStartup: true,
markSuspendedTabs: false
};
let _injectedTabs = new Set();
let _suspending = false;
async function hasHostPermission() {
try {
return await chrome.permissions.contains({ origins: ['<all_urls>'] });
} catch { return false; }
}
async function injectFormCheck(tabId) {
if (_injectedTabs.has(tabId)) return;
if (!(await hasHostPermission())) return;
// Add optimistically before await to prevent concurrent callers from double-injecting
_injectedTabs.add(tabId);
try {
await chrome.scripting.executeScript({
target: { tabId },
files: ['formcheck.js']
});
} catch {
_injectedTabs.delete(tabId);
}
}
const ALARM_NAME = 'check-tabs';
const BADGE_COLOR = '#7c3aed';
const MB_PER_TAB = 150;
const MAX_SESSIONS = 20;
const UNINSTALL_URL = 'https://ml3dev.github.io/drowzy/uninstall.html';
// Versions that open What's New on update despite not being a major bump.
// See onInstalled for why this exists and why it should stay short.
const SHOW_CHANGELOG_VERSIONS = ['1.4.0'];
let badgeTimer = null;
function t(key, subs) {
return chrome.i18n.getMessage(key, subs) || key;
}
chrome.runtime.onInstalled.addListener(onInstalled);
chrome.runtime.onStartup.addListener(onStartup);
chrome.alarms.onAlarm.addListener(onAlarm);
chrome.tabs.onActivated.addListener(onTabActivated);
chrome.tabs.onUpdated.addListener(onTabUpdated);
chrome.tabs.onCreated.addListener(onTabCreated);
chrome.tabs.onRemoved.addListener(onTabRemoved);
chrome.tabs.onReplaced.addListener(onTabReplaced);
chrome.contextMenus.onClicked.addListener(onContextMenuClicked);
chrome.commands.onCommand.addListener(onCommand);
chrome.runtime.onMessage.addListener(onMessage);
// Refresh the badge when the user switches between Chrome windows, so the
// window-scoped count reflects the focused window. WINDOW_ID_NONE means focus
// moved out of Chrome entirely - let updateBadgeNow clear the badge.
try {
if (chrome.windows && chrome.windows.onFocusChanged) {
chrome.windows.onFocusChanged.addListener(function() {
debouncedBadgeUpdate();
});
}
} catch {}
// Reset host-gated settings when user revokes optional host permission
chrome.permissions.onRemoved.addListener(async (permissions) => {
if (permissions.origins && permissions.origins.includes('<all_urls>')) {
let settings = await getSettings();
let changed = false;
if (settings.protectForms) { settings.protectForms = false; changed = true; }
if (settings.markSuspendedTabs) { settings.markSuspendedTabs = false; changed = true; }
if (changed) await chrome.storage.sync.set({ settings });
}
});
async function onInstalled(details) {
await initSettings();
await createAlarm();
createContextMenus();
await initTimestamps();
await updateBadgeNow();
try { await chrome.runtime.setUninstallURL(UNINSTALL_URL); } catch {}
// Sync host-gated settings with actual permission state
try {
let hasHost = await hasHostPermission();
if (!hasHost) {
let settings = await getSettings();
let changed = false;
if (settings.protectForms) { settings.protectForms = false; changed = true; }
if (settings.markSuspendedTabs) { settings.markSuspendedTabs = false; changed = true; }
if (changed) await chrome.storage.sync.set({ settings });
}
} catch {}
if (details.reason === 'install') {
await initStats();
await chrome.storage.local.set({ drowzy_lastChangelogVersion: chrome.runtime.getManifest().version });
try { chrome.tabs.create({ url: 'onboarding.html' }); } catch {}
// first-run quick-suspend: without this the user waits the full 15 min
// (default) before anything visibly happens, which is the most common
// reason cited for "didn't notice a memory difference" and uninstalling.
// ~30s after install, suspend tabs Chrome reports as idle for 10+ minutes
// - only the obviously-stale ones, so it doesn't surprise the user with
// a recently-used tab going away. Uses chrome.alarms (not setTimeout) so
// the pass survives MV3 service-worker termination during the wait.
try { chrome.alarms.create('first-run-suspend', { delayInMinutes: 0.5 }); } catch {}
} else if (details.reason === 'update') {
let version = chrome.runtime.getManifest().version;
let data = await chrome.storage.local.get('drowzy_lastChangelogVersion');
let lastVer = data.drowzy_lastChangelogVersion || '';
// Only show changelog on MAJOR version bumps (e.g. 1.x.x → 2.x.x).
// Minor and patch bumps silently update the stored version.
//
// SHOW_CHANGELOG_VERSIONS is a narrow opt-in for releases where the whole
// point is telling people what changed. 1.4.0 adds a per-tab hold and
// explains why tabs are protected, both of which are invisible unless you
// go looking. Keep this list short - a What's New tab that opens for every
// release is just noise, which is why the major-bump rule is still the
// default for everything not listed here.
let curMajor = version.split('.')[0];
let lastMajor = lastVer.split('.')[0];
let forced = SHOW_CHANGELOG_VERSIONS.includes(version) && lastVer !== version;
if (lastVer && (forced || curMajor !== lastMajor)) {
await chrome.storage.local.set({ drowzy_lastChangelogVersion: version });
try { chrome.tabs.create({ url: 'changelog.html' }); } catch {}
} else if (lastVer !== version) {
await chrome.storage.local.set({ drowzy_lastChangelogVersion: version });
}
}
}
async function onStartup() {
await createAlarm();
// Rebuild context menus on every startup. They're created once at install in
// the then-current UI language and don't otherwise refresh, so a user who
// changes Chrome's display language would keep stale-language menu items
// until the next reload. createContextMenus() removes-all-then-recreates and
// re-reads chrome.i18n, so this picks up a language change on next launch.
createContextMenus();
await initTimestamps();
await updateBadgeNow();
// Re-affirm in case it was cleared or we updated the URL since install
try { await chrome.runtime.setUninstallURL(UNINSTALL_URL); } catch {}
let settings = await getSettings();
if (settings.suspendOnStartup) {
// Use an alarm rather than setTimeout. Once onStartup's awaits resolve the
// service worker has no pending events keeping it alive: a 5s timer can
// miss its deadline if the worker is terminated first. Alarms survive
// worker death. 0.1 min gets clamped to ~30s in production, which is also
// enough delay for Chrome to finish restoring saved tabs.
try { chrome.alarms.create('startup-suspend', { delayInMinutes: 0.1 }); } catch {}
// Chrome restores big sessions progressively (deferred windows, staggered
// background loading), so tabs can keep materializing long after startup.
// Instead of stacking one-shot alarms, tag everything that is a restore
// artifact right now; restoredCatchupSweep drains the tag set from the
// 30s alarm above and then the per-minute check-tabs tick, so even a
// session that takes ten minutes to restore is fully covered. Tabs
// restored later still are tagged as they appear (onTabCreated). Each
// window's startup-active tab is instead seeded as viewed - it is on the
// user's screen right now, and without this a tab they look at and then
// switch away from before the sweep runs would be swept.
try {
let all = await chrome.tabs.query({});
let pending = await loadRestoredPending();
let added = false;
for (let tab of all) {
if (tab.active) {
await markActivated(tab.id);
continue;
}
if (tab.discarded) continue;
if (!pending.has(tab.id)) { pending.add(tab.id); added = true; }
}
if (added) await persistRestoredPending();
} catch {}
}
}
async function firstRunQuickSuspend() {
// Conservative first-run pass. Uses tab.lastAccessed (Chrome 121+) so we
// only touch tabs Chrome itself confirms have been idle for a while; on
// 120 (no lastAccessed), we skip - better to miss the boost than surprise
// a fresh installer with a tab they were just using.
try {
let settings = await getSettings();
if (!settings.enableAutoSuspend) return;
// this pass discards directly rather than through suspendTab, so it needs
// its own Keep-awake check. In practice no hold can exist 30s after
// install, but the bypass should not be the one path that ignores it.
await loadKeptAwake();
let tabs = await chrome.tabs.query({});
let staleBefore = Date.now() - 10 * 60 * 1000;
for (let tab of tabs) {
if (tab.active || tab.discarded) continue;
if (_keptAwake.has(tab.id)) continue;
if (typeof tab.lastAccessed !== 'number') continue;
if (tab.lastAccessed > staleBefore) continue;
if (isInternalUrl(tab.url)) continue;
if (settings.protectPinned && tab.pinned) continue;
if (settings.protectAudio && tab.audible) continue;
if (isWhitelisted(tab.url, settings.whitelist)) continue;
try {
let result = await chrome.tabs.discard(tab.id);
if (result) await recordSuspension(tab.id);
} catch {}
}
await updateBadgeNow();
} catch {}
}
// Tab ids that are session-restore artifacts still owed a re-suspend: seeded
// at startup (everything non-active), extended as late-restored tabs appear
// (onTabCreated), and drained by restoredCatchupSweep. Backed by
// chrome.storage.session - cleared on browser restart, survives MV3
// service-worker restarts in between.
//
// Both session sets memoize the IN-FLIGHT PROMISE, not the resolved value:
// concurrent first callers (onStartup seeding vs an onTabCreated burst) must
// share one Set. Caching the value would let a second caller's storage read
// clobber a Set the first caller already mutated, silently dropping tags.
let _restoredPendingPromise = null;
let _restoredPersistTimer = null;
function loadRestoredPending() {
if (!_restoredPendingPromise) {
_restoredPendingPromise = chrome.storage.session.get('restoredTabIds')
.then(function(data) { return new Set(data.restoredTabIds || []); })
.catch(function() { return new Set(); });
}
return _restoredPendingPromise;
}
async function persistRestoredPending() {
try {
let set = await loadRestoredPending();
await chrome.storage.session.set({ restoredTabIds: [...set] });
} catch {}
}
function scheduleRestoredPersist() {
// restores create tabs in bursts; rewriting the whole array per tab would
// be O(n^2) during the exact burst this feature targets - coalesce writes.
// A write lost to worker death degrades gracefully: an untagged tab just
// falls back to the normal idle timer.
if (_restoredPersistTimer) return;
_restoredPersistTimer = setTimeout(function() {
_restoredPersistTimer = null;
persistRestoredPending();
}, 1000);
}
async function tagRestored(tabId) {
let set = await loadRestoredPending();
if (set.has(tabId)) return;
set.add(tabId);
scheduleRestoredPersist();
}
async function untagRestored(tabId) {
let set = await loadRestoredPending();
if (!set.has(tabId)) return;
set.delete(tabId);
await persistRestoredPending();
}
async function clearRestoredPending() {
let set = await loadRestoredPending();
if (!set.size) return;
set.clear();
await persistRestoredPending();
}
let _sweeping = false;
async function restoredCatchupSweep(settings) {
// startup catch-up: re-suspend restore-tagged tabs the user hasn't viewed.
// Runs from the 30s startup-suspend alarm AND the existing per-minute tick
// until the tag set drains, so a session that restores slowly is covered
// minute by minute rather than by fixed-delay passes. Guards:
// 1. tabs the user has actually VIEWED this session are left alone (see
// the activated set). A time-based guard would misfire here: restore
// itself bumps timestamps, so late-restored tabs - the exact
// stragglers this sweep targets - would look "recently touched".
// 2. tabs still mid-load stay tagged and are retried next tick;
// discarding a tab whose navigation hasn't committed can revert it to
// a stale URL. suspendTab gets skipLoading so its FRESH pre-discard
// recheck enforces this too - the snapshot alone could miss a load
// that started mid-sweep. Still-unloaded tabs ARE swept - discarding
// them before Chrome's tab loader gets to them prevents the RAM
// spike entirely.
// 3. every other outcome untags: suspended, closed, viewed, or protected
// (pinned/audio/whitelist/internal via shouldSuspend). From then on
// the tab belongs to the normal idle timer, so the sweep converges
// to a no-op instead of re-checking the same tabs forever.
// Suspends go through suspendTab, so protectForms / markSuspendedTabs and
// the final pre-discard recheck all apply.
if (_sweeping) return; // the 30s alarm and the per-minute tick can overlap
_sweeping = true;
try {
let pending = await loadRestoredPending();
if (!pending.size) return;
let activated = await loadActivatedSet();
let tabs = await chrome.tabs.query({});
let now = Date.now();
let byId = new Map();
for (let tab of tabs) byId.set(tab.id, tab);
let dirty = false;
for (let id of [...pending]) {
let tab = byId.get(id);
if (!tab) {
// absent from the snapshot: usually closed - but a tab created and
// tagged during this sweep's own awaits is also absent, so confirm
// it is truly gone before untagging (it sweeps next tick otherwise)
try {
await chrome.tabs.get(id);
} catch {
pending.delete(id);
dirty = true;
}
continue;
}
if (tab.discarded || tab.active || activated.has(id)) {
pending.delete(id); dirty = true; continue;
}
if (tab.status === 'loading') continue;
seedTimestamp(tab, now);
// untag BEFORE the discard: a discard swaps the tab id via onReplaced,
// and the tag must not outlive the suspend - a tab Drowzy just put to
// sleep is done, and re-tagging its new id would let the sweep discard
// it again right after a Wake All reloads it in the background.
pending.delete(id);
dirty = true;
// threshold 0 = shouldSuspend's eligibility checks only (active,
// discarded, internal, pinned, audio, whitelist) with no idle
// requirement - the idle rule for this sweep is the activated-set guard
if (shouldSuspend(tab, settings, _timestamps, now, 0)) {
let suspended = await suspendTab(tab.id, settings, { skipLoading: true });
if (!suspended) {
// suspendTab's fresh recheck may have refused because a load
// started after our snapshot - re-tag that one case so it retries
// next tick, same as a load that was visible in the snapshot.
// Other refusals (activated, audible, form data) stay untagged.
try {
let fresh = await chrome.tabs.get(id);
if (fresh.status === 'loading' && !fresh.active && !fresh.discarded) {
pending.add(id);
}
} catch {}
}
}
}
if (dirty) await persistRestoredPending();
if (_tsDirty) scheduleFlush();
} catch {} finally {
_sweeping = false;
}
}
// Tab ids the user has actually activated (viewed) this browser session.
// Backed by chrome.storage.session, which Chrome clears on browser restart -
// exactly the "this session" lifetime we want - and which survives MV3
// service-worker restarts in between. Same in-flight-promise memoization as
// the restored-pending set, for the same clobbering reason.
let _activatedPromise = null;
function loadActivatedSet() {
if (!_activatedPromise) {
_activatedPromise = chrome.storage.session.get('activatedTabIds')
.then(function(data) { return new Set(data.activatedTabIds || []); })
.catch(function() { return new Set(); });
}
return _activatedPromise;
}
async function persistActivatedSet() {
try {
let set = await loadActivatedSet();
await chrome.storage.session.set({ activatedTabIds: [...set] });
} catch {}
}
async function markActivated(tabId) {
try {
let set = await loadActivatedSet();
if (set.has(tabId)) return;
set.add(tabId);
await persistActivatedSet();
} catch {}
}
async function unmarkActivated(tabId) {
try {
let set = await loadActivatedSet();
if (!set.has(tabId)) return;
set.delete(tabId);
await persistActivatedSet();
} catch {}
}
// Tab ids the user has explicitly held awake ("Keep this tab awake"). Same
// chrome.storage.session backing and in-flight-promise memoization as the two
// sets above, for the same clobbering reason. Clearing on browser restart is
// the point, not a limitation: a hold is a "not right now" decision about one
// tab in front of you. The whitelist stays the permanent, per-site tool.
//
// Unlike the other two, the Set is also exposed as a module-level mirror,
// because shouldSuspend is synchronous and cannot await. Every caller of
// shouldSuspend awaits loadKeptAwake() first, so the mirror is warm by then;
// suspendTab does its own await and is the authoritative gate.
let _keptAwakePromise = null;
let _keptAwake = new Set();
function loadKeptAwake() {
if (!_keptAwakePromise) {
// fill the existing Set in place rather than replacing it - the mirror
// and the promised value must stay the same object, or a mutation made
// through one would be invisible to the other
_keptAwakePromise = chrome.storage.session.get('keptAwakeTabIds')
.then(function(data) {
for (let id of (data.keptAwakeTabIds || [])) _keptAwake.add(id);
return _keptAwake;
})
.catch(function() { return _keptAwake; });
}
return _keptAwakePromise;
}
async function persistKeptAwake() {
try {
let set = await loadKeptAwake();
await chrome.storage.session.set({ keptAwakeTabIds: [...set] });
} catch {}
}
async function setKeptAwake(tabId, on) {
try {
let set = await loadKeptAwake();
if (on === set.has(tabId)) return on;
if (on) set.add(tabId); else set.delete(tabId);
// persist immediately, no debounce: these are one-at-a-time user actions,
// and a hold lost to worker death would silently suspend a tab the user
// just asked to keep
await persistKeptAwake();
return on;
} catch { return false; }
}
async function isKeptAwake(tabId) {
try {
let set = await loadKeptAwake();
return set.has(tabId);
} catch { return false; }
}
// Chrome drops tab.favIconUrl once a tab is discarded, so the moment you hit
// Suspend Others the list turns into a wall of anonymous letter circles - the
// icons vanish exactly when the tab list matters most. Remember the last icon
// we saw per tab and serve it back when Chrome has none. Same session backing
// and memoization as the sets above; cleared on browser restart, which is
// fine because Chrome re-reports favicons as tabs reload.
let _faviconsPromise = null;
let _favicons = {};
let _favDirty = false;
let _favTimer = null;
function loadFavicons() {
if (!_faviconsPromise) {
_faviconsPromise = chrome.storage.session.get('tabFavicons')
.then(function(data) {
let stored = data.tabFavicons || {};
// fill in place, never replace: a favicon remembered before the read
// resolved must not be lost (same reasoning as the sets above)
for (let id in stored) if (!(id in _favicons)) _favicons[id] = stored[id];
return _favicons;
})
.catch(function() { return _favicons; });
}
return _faviconsPromise;
}
function rememberFavicon(tabId, url) {
// chrome:// icons are not renderable from the popup, so caching them would
// just reintroduce the broken-image path buildFavicon already guards against
if (!url || url.indexOf('chrome://') === 0) return;
if (_favicons[tabId] === url) return;
_favicons[tabId] = url;
_favDirty = true;
// debounced: navigation churn would otherwise rewrite the whole map per hop
if (_favTimer) return;
_favTimer = setTimeout(function() { _favTimer = null; flushFavicons(); }, 3000);
}
async function flushFavicons() {
if (!_favDirty) return;
try {
await chrome.storage.session.set({ tabFavicons: _favicons });
_favDirty = false;
} catch {}
}
// Why a suspend was refused, for the failure toast. Called ONLY after a
// suspend attempt already returned false, so it costs nothing on the happy
// path and cannot influence whether a tab is discarded. Returns an i18n key
// or null when we genuinely do not know (Chrome refused for its own reasons).
async function explainSuspendFailure(tabId, cachedSettings) {
try {
let tab = await chrome.tabs.get(tabId);
// Already asleep: auto-suspend beat the click, or the tab was discarded
// between render and click. The user got what they asked for, so the
// caller must report success rather than an error toast.
if (tab.discarded) return 'ALREADY_ASLEEP';
if (isInternalUrl(tab.url)) return 'systemPageCantSuspend';
if (await isKeptAwake(tabId)) return 'keptAwakeWontSuspend';
let settings = cachedSettings || await getSettings();
if (settings.protectPinned && tab.pinned) return 'pinnedWontSuspend';
if (settings.protectAudio && tab.audible) return 'audioWontSuspend';
if (isWhitelisted(tab.url, settings.whitelist)) return 'whitelistedWontSuspend';
if (tab.active) return 'cantSuspendNoOtherTab';
if (tab.status === 'loading') return 'suspendFailedLoading';
// form data is the only remaining reason we can still ask about, and only
// when the setting that would have blocked it is actually on
if (settings.protectForms) {
try {
let resp = await Promise.race([
chrome.tabs.sendMessage(tabId, { action: 'checkFormData' }),
new Promise(resolve => setTimeout(() => resolve(null), 500))
]);
if (resp && resp.hasFormData) return 'suspendFailedForm';
} catch {}
}
return null;
} catch { return null; }
}
let _timestamps = {};
let _tsDirty = false;
let _tsFlushTimer = null;
async function initTimestamps() {
try {
let data = await chrome.storage.session.get('tabTimestamps');
_timestamps = data.tabTimestamps || {};
let tabs = await chrome.tabs.query({});
let now = Date.now();
let liveIds = new Set(tabs.map(tab => tab.id));
// Add missing tabs (see seedTimestamp for the lastAccessed reasoning)
for (let tab of tabs) {
seedTimestamp(tab, now);
}
// Prune stale tab IDs that no longer exist
for (let id in _timestamps) {
if (!liveIds.has(Number(id))) {
delete _timestamps[id];
_tsDirty = true;
}
}
// Same prune for Keep-awake holds. onTabRemoved normally clears these, but
// a removal that lands while the worker is down would leave the id behind
// forever. Harmless today (Chrome does not recycle tab ids within a
// session) but it would quietly grow the stored array.
try {
let held = await loadKeptAwake();
let stale = [...held].filter(id => !liveIds.has(id));
if (stale.length) {
for (let id of stale) held.delete(id);
await persistKeptAwake();
}
// same prune for the remembered favicons, which would otherwise be the
// one session map that grows for the whole browser session
await loadFavicons();
for (let id in _favicons) {
if (!liveIds.has(Number(id))) { delete _favicons[id]; _favDirty = true; }
}
await flushFavicons();
} catch {}
await flushTimestamps();
} catch {}
}
function seedTimestamp(tab, now) {
// Seed an untracked tab from Chrome's own tab.lastAccessed (121+) when
// available, so a service-worker restart with cleared session storage
// doesn't reset the apparent idle time of long-untouched tabs to NOW -
// that would silently grant every tab a fresh full timer on restart.
if (tab.id in _timestamps) return;
_timestamps[tab.id] = (typeof tab.lastAccessed === 'number') ? tab.lastAccessed : now;
_tsDirty = true;
}
function scheduleFlush() {
if (_tsFlushTimer) return;
_tsFlushTimer = setTimeout(() => {
_tsFlushTimer = null;
flushTimestamps();
}, 5000);
}
async function flushTimestamps() {
if (!_tsDirty) return;
try {
await chrome.storage.session.set({ tabTimestamps: _timestamps });
_tsDirty = false;
} catch {}
}
/* settings */
async function initSettings() {
let synced = await chrome.storage.sync.get('settings');
if (synced.settings) return;
let local = await chrome.storage.local.get('settings');
if (local.settings) {
await chrome.storage.sync.set({ settings: local.settings });
await chrome.storage.local.remove('settings');
return;
}
await chrome.storage.sync.set({ settings: DEFAULT_SETTINGS });
}
async function getSettings() {
let stored = await chrome.storage.sync.get('settings');
if (!stored.settings) return { ...DEFAULT_SETTINGS };
let merged = { ...DEFAULT_SETTINGS, ...stored.settings };
if (!Array.isArray(merged.whitelist)) merged.whitelist = [];
merged.whitelist = merged.whitelist.map(w => w.toLowerCase().replace(/^www\./, ''));
return merged;
}
async function initStats() {
let data = await chrome.storage.local.get('drowzy_stats');
if (!data.drowzy_stats) {
await chrome.storage.local.set({
drowzy_stats: {
totalTabsSuspended: 0,
totalTabsSuspendedToday: 0,
todayDate: _localDate(),
installDate: Date.now()
}
});
}
}
function _localDate() {
let d = new Date();
return d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0');
}
function _defaultStats() {
return {
totalTabsSuspended: 0,
totalTabsSuspendedToday: 0,
todayDate: _localDate(),
installDate: Date.now()
};
}
// Stats are meant to count tabs going to sleep, not button presses. Suspend
// Others followed by Wake All, in a loop, otherwise inflates the lifetime
// figures without limit: the numbers stop meaning anything and the stat cards
// fill with absurd values. A tab re-slept within a minute of last being
// counted does not count again. Genuine use is unaffected - nobody legitimately
// wakes and re-sleeps the same tab twice inside sixty seconds.
//
// In memory on purpose: it only has to outlive a burst of clicking, and the
// worker is alive throughout one.
const RECOUNT_COOLDOWN_MS = 60 * 1000;
let _lastCounted = new Map();
function countsAsNewSuspension(tabId) {
let now = Date.now();
let prev = _lastCounted.get(tabId);
if (prev && now - prev < RECOUNT_COOLDOWN_MS) return false;
_lastCounted.set(tabId, now);
if (_lastCounted.size > 500) {
for (let [id, ts] of _lastCounted) {
if (now - ts > RECOUNT_COOLDOWN_MS) _lastCounted.delete(id);
}
}
return true;
}
async function recordSuspension(tabId) {
if (typeof tabId === 'number' && !countsAsNewSuspension(tabId)) return;
try {
let data = await chrome.storage.local.get('drowzy_stats');
let stats = data.drowzy_stats || _defaultStats();
let today = _localDate();
if (stats.todayDate !== today) {
stats.totalTabsSuspendedToday = 0;
stats.todayDate = today;
}
stats.totalTabsSuspended++;
stats.totalTabsSuspendedToday++;
await chrome.storage.local.set({ drowzy_stats: stats });
} catch {}
}
async function getStats() {
let data = await chrome.storage.local.get('drowzy_stats');
let stats = data.drowzy_stats || _defaultStats();
let today = _localDate();
if (stats.todayDate !== today) {
stats.totalTabsSuspendedToday = 0;
stats.todayDate = today;
await chrome.storage.local.set({ drowzy_stats: stats });
}
return stats;
}
async function createAlarm() {
let existing = await chrome.alarms.get(ALARM_NAME);
if (!existing) {
chrome.alarms.create(ALARM_NAME, { periodInMinutes: 1 });
}
}
async function onAlarm(alarm) {
if (alarm.name === ALARM_NAME) await checkAndSuspendTabs();
else if (alarm.name === 'first-run-suspend') await firstRunQuickSuspend();
else if (alarm.name === 'startup-suspend') {
// same guarded sweep the per-minute tick runs - one mechanism, fired
// early. (Before 1.3.8 this pass was a raw discard-everything loop that
// ignored viewed and mid-load tabs; the sweep keeps its speed but adds
// those protections.)
let settings = await getSettings();
// warm the Keep-awake mirror here too, so "loaded before any shouldSuspend
// call" holds on every path rather than only on the per-minute tick. At
// startup the set is always empty (session storage is cleared on restart),
// but relying on that is a reasoning trap the next change would fall into.
await loadKeptAwake();
if (settings.suspendOnStartup) await restoredCatchupSweep(settings);
}
}
async function onTabActivated(activeInfo) {
await touchTab(activeInfo.tabId);
await markActivated(activeInfo.tabId);
// the user is looking at it now - it is no longer the startup sweep's business
await untagRestored(activeInfo.tabId);
// Flush immediately on activation since worker is alive during this event
await flushTimestamps();
debouncedBadgeUpdate();
}
async function onTabUpdated(tabId, changeInfo, tab) {
// capture the icon while the tab still has one - after a discard it is gone
if (changeInfo.favIconUrl) rememberFavicon(tabId, changeInfo.favIconUrl);
else if (tab && tab.favIconUrl && !tab.discarded) rememberFavicon(tabId, tab.favIconUrl);
if (changeInfo.status === 'complete' || changeInfo.url) {
await touchTab(tabId);
}
// Audio going quiet (pause, mute, call ending) counts as activity so the
// tab gets the full suspend threshold before becoming eligible. Prevents
// paused-Spotify / ended-meeting tabs from being suspended immediately
// after their audible flag drops, which would force a full page reload.
if (changeInfo.audible === false) {
await touchTab(tabId);
}
// Content scripts are torn down on navigation AND reload. Drop the
// _injectedTabs marker on either a URL change or when the page starts
// loading again (covers manual reload / browser restore where URL stays).
if (changeInfo.url || changeInfo.status === 'loading') {
_injectedTabs.delete(tabId);
}
if (changeInfo.discarded !== undefined) debouncedBadgeUpdate();
}
async function onTabCreated(tab) {
await touchTab(tab.id);
if (tab.active) {
// born on the user's screen (new tab, or the active tab of a late-restored
// window that onStartup's seeding query ran too early to see) - count it
// as viewed so the startup catch-up sweep leaves it alone
await markActivated(tab.id);
} else if (tab.status === 'unloaded' || tab.discarded) {
// born in the background with no content: that's the shape of a
// session-restored (or reopened) tab, not one the user opened - tabs a
// user opens in the background (middle-click, "open in new tab") start
// loading immediately. Tag it for the startup catch-up sweep.
await tagRestored(tab.id);
}
}
async function onTabRemoved(tabId) {
_injectedTabs.delete(tabId);
await untagRestored(tabId);
await unmarkActivated(tabId);
// a hold dies with its tab - ids get recycled, and inheriting a stranger's
// hold would keep a brand new tab awake for no visible reason
await setKeptAwake(tabId, false);
if (tabId in _favicons) { delete _favicons[tabId]; _favDirty = true; }
_lastCounted.delete(tabId);
// Only mark dirty if we actually removed a tracked timestamp - avoids
// flushing session storage when the tab wasn't being tracked.
if (tabId in _timestamps) {
delete _timestamps[tabId];
_tsDirty = true;
// Flush immediately - worker may be killed before a scheduled flush runs
await flushTimestamps();
}
debouncedBadgeUpdate();
}
async function onTabReplaced(addedTabId, removedTabId) {
_timestamps[addedTabId] = _timestamps[removedTabId] || Date.now();
delete _timestamps[removedTabId];
_tsDirty = true;
scheduleFlush();
// a discard swaps the tab id - carry viewed-this-session membership over
// so the sweep still recognizes the tab under its new id. The restore tag
// is deliberately NOT transferred: onReplaced here means the tab was just
// discarded (usually by Drowzy itself), so the sweep's job for it is done.
// Carrying the tag would let the sweep re-discard the tab right after a
// Wake All reloads it in the background without activating it.
try {
let set = await loadActivatedSet();
if (set.has(removedTabId)) {
set.delete(removedTabId);
set.add(addedTabId);
await persistActivatedSet();
}
await untagRestored(removedTabId);
// a discard swaps the id, and the discarded tab has no favicon of its own -
// carrying the remembered one across is the whole point of the cache
if (removedTabId in _favicons) {
_favicons[addedTabId] = _favicons[removedTabId];
delete _favicons[removedTabId];
_favDirty = true;
await flushFavicons();
}
// carry the hold across the id swap. The user held the page, not the id,
// and a prerender/discard swap is invisible to them.
let held = await loadKeptAwake();
if (held.has(removedTabId)) {
held.delete(removedTabId);
held.add(addedTabId);
await persistKeptAwake();
}
} catch {}
}
async function touchTab(tabId) {
_timestamps[tabId] = Date.now();
_tsDirty = true;
scheduleFlush();
}
async function checkAndSuspendTabs() {
// Guard against concurrent alarm firings (2.5s warning delay can overlap)
if (_suspending) return;
_suspending = true;
try {
// Lazy-reload timestamps if service worker restarted mid-session
if (Object.keys(_timestamps).length === 0) {
await initTimestamps();
}
let settings = await getSettings();
// warm the Keep-awake mirror before anything calls shouldSuspend, which
// reads it synchronously. Cheap after the first tick: memoized promise.
await loadKeptAwake();
// startup catch-up runs before (and independently of) the auto-suspend
// gates below: "Suspend tabs on startup" works even when auto-suspend is
// off or the timer is set to Never. The sweep queries tabs itself only
// while tags are pending, so the steady state adds no work here.
if (settings.suspendOnStartup) {
await restoredCatchupSweep(settings);
} else {
// feature off: drop any tags onTabCreated accumulated, so toggling it
// on later can't trigger a surprise mass discard of tabs reopened
// while it was off
await clearRestoredPending();
}
if (!settings.enableAutoSuspend) return;
let minutes = Number(settings.suspendAfterMinutes);
if (!minutes || minutes <= 0) return;
let tabs = await chrome.tabs.query({});
let now = Date.now();
let threshold = minutes * 60 * 1000;
let toSuspend = [];
for (let tab of tabs) {
seedTimestamp(tab, now);
if (shouldSuspend(tab, settings, _timestamps, now, threshold)) {
toSuspend.push(tab.id);
}
}
if (_tsDirty) scheduleFlush();
if (toSuspend.length) {
for (let tabId of toSuspend) {
await injectFormCheck(tabId);
try { await chrome.tabs.sendMessage(tabId, { action: 'suspendWarning' }); } catch {}
}
await new Promise(r => setTimeout(r, 2500));
for (let tabId of toSuspend) {
// auto:true so suspendTab respects a Keep awake / refocus that landed
// during the warning window. Manual suspends bypass this check.
await suspendTab(tabId, settings, { auto: true });
}
}
} finally { _suspending = false; }
}
function shouldSuspend(tab, settings, timestamps, now, threshold) {
if (tab.active || tab.discarded) return false;
// Reads the sync mirror. suspendTab re-checks authoritatively, so this is
// not the gate that keeps the tab alive - it is here so a held tab never
// gets a "Suspending tab soon..." banner for a suspend that cannot happen.
if (_keptAwake.has(tab.id)) return false;
if (isInternalUrl(tab.url)) return false;
if (settings.protectPinned && tab.pinned) return false;
if (settings.protectAudio && tab.audible) return false;
if (isWhitelisted(tab.url, settings.whitelist)) return false;
let lastActive = timestamps[tab.id] || 0;
// tab.lastAccessed (Chrome 121+) is what Chrome itself tracks for tab activation;
// prefer the more recent of our timestamp and Chrome's so a tab activated
// before the service worker came up isn't immediately suspendable.
if (typeof tab.lastAccessed === 'number' && tab.lastAccessed > lastActive) {
lastActive = tab.lastAccessed;
}
return lastActive && (now - lastActive >= threshold);
}
function isInternalUrl(url) {
if (!url) return true;
try {
let protocol = new URL(url).protocol;
return protocol !== 'http:' && protocol !== 'https:';
} catch { return true; }
}
function isWhitelisted(url, whitelist) {
if (!url || !whitelist || !whitelist.length) return false;
try {
let parsed = new URL(url);
let hostname = parsed.hostname.toLowerCase().replace(/^www\./, '');
let fullUrl = (parsed.hostname + parsed.pathname).toLowerCase().replace(/^www\./, '');
return whitelist.some(d => {
d = d.toLowerCase().replace(/^www\./, '');
if (d.includes('/')) {
let escaped = d.replace(/[.*+?^${}()|[\]\\]/g, '\\$&').replace(/\\\*/g, '.*');
try { return new RegExp('^' + escaped + '(/.*)?$').test(fullUrl); } catch { return false; }
}
return hostname === d || hostname.endsWith('.' + d);
});
} catch { return false; }
}
async function suspendTab(tabId, cachedSettings, opts) {
try {
let tab = await chrome.tabs.get(tabId);
if (tab.active || tab.discarded) return false;
if (isInternalUrl(tab.url)) return false;
let settings = cachedSettings || await getSettings();
if (settings.protectPinned && tab.pinned) return false;
if (settings.protectAudio && tab.audible) return false;
if (isWhitelisted(tab.url, settings.whitelist)) return false;
// The authoritative Keep-awake gate. Every suspend path except
// firstRunQuickSuspend funnels through here, including the startup catch-up
// sweep, so this one await covers auto-suspend, Suspend Others, Suspend
// this tab, the context menu, the shortcut, and the sweep. Checked before
// injectFormCheck so a held tab never gets a content script injected for a
// suspend that will not happen.
if (await isKeptAwake(tabId)) return false;
if (settings.protectForms || settings.markSuspendedTabs) {
await injectFormCheck(tabId);
}