blob: 55990f3347ca3a0d522eaf1e671bf4c7a4a2b511 [file] [log] [blame]
Adrià Vilanova Martínez9ff52fe2022-09-15 12:27:49 +02001// WARNING: In MV2, data is persisted even after the session ends,[1] unlike
2// with chrome.storage.session in MV3.
3//
4// Before, this class in MV2 only persisted data until the background page was
5// unloaded, so this introduced bug
6// https://iavm.xyz/b/translateselectedtext/18.
7//
8// Thus, since making the background page persistent will impact performance,
9// the easiest solution is to let this custom session storage be persistent in
10// MV2, because persistence of this storage won't affect the extension, and
11// although this solution isn't nice and could introduce some smaller bugs, MV2
12// will be deprecated soon anyways.
13//
14// [1]: The only exception is the translatorTab value, which will be erased when
15// the corresponding tab is closed. This is because after a browser restart,
16// already used tab IDs can be reused again, so we could end up opening Google
17// Translate in an unrelated tab otherwise.
18//
19// Also, we'll delete this value when starting the browser as another
20// "protection layer", since closing the browser sometimes results in the
21// onRemoved event not being handled.
22//
23// Keep in mind there are some edge cases where we could still be reusing an
24// unrelated tab. A known one is when the extension is disabled for some period
25// of time and afterwards enabled again, but there might be others.
26
27chrome.runtime.onStartup.addListener(() => {
28 chrome.storage.local.remove('translatorTab');
29});
30
31chrome.tabs.onRemoved.addListener(tabId => {
32 ExtSessionStorage.get('translatorTab').then(items => {
33 if (tabId === items['translatorTab'])
34 chrome.storage.local.remove('translatorTab');
35 });
36});
Adrià Vilanova Martínez5bdc4732022-05-31 20:12:21 +020037
Adrià Vilanova Martínez86fda492022-05-31 15:05:21 +020038export default class ExtSessionStorage {
Adrià Vilanova Martínez5bdc4732022-05-31 20:12:21 +020039 static set(items: any): Promise<void> {
Adrià Vilanova Martínez9ff52fe2022-09-15 12:27:49 +020040 return chrome.storage.local.set(items);
Adrià Vilanova Martínez86fda492022-05-31 15:05:21 +020041 }
42
Adrià Vilanova Martínez5bdc4732022-05-31 20:12:21 +020043 static get(keys: string|Array<string>|undefined): Promise<any> {
Adrià Vilanova Martínez9ff52fe2022-09-15 12:27:49 +020044 return new Promise((res, _) => {
45 chrome.storage.local.get(keys, items => {
46 res(items);
47 });
Adrià Vilanova Martínez86fda492022-05-31 15:05:21 +020048 });
49 }
50}