diff --git a/src/background.js b/src/background.js index d2d0497..919db16 100644 --- a/src/background.js +++ b/src/background.js @@ -1,6 +1,6 @@ import browser from 'webextension-polyfill'; -import { addTab, deleteData, isStorageV1, loadData, migrateStorageToV2, storeData } from "./data"; +import { addTab, deleteData, isStorageV1, loadData, migrateStorageToV2, storeData, switchData } from "./data"; const MAX_MATCHING_URLS_SIZE = 100; let matchingUrls = new Map(); @@ -124,6 +124,9 @@ browser.runtime.onMessage.addListener( case "deleteData": deleteData(sender.tab.id, message.payload); break; + case "switchData": + switchData(sender.tab.id, message.payload); + break; } } ); diff --git a/src/data.js b/src/data.js index 928d84b..086383d 100644 --- a/src/data.js +++ b/src/data.js @@ -173,3 +173,27 @@ export async function deleteData(tabId, location) { broadcastMessage(data, clientUrl); } } + +export async function switchData(tabId, location) { + const clientUrl = await getTabClientUrl(tabId); + const data = await dataLock.acquire("clientData", async () => { + const rootKey = `currentRoot;${clientUrl}`; + const rootsKey = `roots;${clientUrl}`; + let {[rootKey]: homeRoot, [rootsKey]: roots} = await browser.storage.local.get([rootKey, rootsKey]); + if (roots == null) { + roots = []; + } + + if (!location || location === homeRoot || roots.find(r => r.url === location) == null) { + return loadedData(); + } + await browser.storage.local.set({[rootKey]: location}); + + const dataKey = `clientData;${clientUrl};${location}`; + const {[dataKey]: clientData} = await browser.storage.local.get(dataKey); + return loadedData(location, clientData, roots); + }); + if (data != null) { + broadcastMessage(data, clientUrl); + } +}