Skip to content

Commit

Permalink
Fix background script set up running every time the background script…
Browse files Browse the repository at this point in the history
…/service worker is restarted (#133)
  • Loading branch information
david-tejada authored Jun 6, 2023
1 parent 2e93aa3 commit 1366881
Show file tree
Hide file tree
Showing 3 changed files with 79 additions and 69 deletions.
132 changes: 69 additions & 63 deletions src/background/setup/initBackgroundScript.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,10 @@ import { urls } from "../../common/urls";
import { watchNavigation } from "../hints/watchNavigation";
import { trackRecentTabs } from "./trackRecentTabs";

// We only need this function temporarily while the users go from a version
// below 0.3.5 to a version equal or above it. To be removed in the future.
/**
* We only need this function temporarily while the users go from a version
* below 0.3.5 to a version equal or above it. To be removed in the future.
*/
async function switchToSyncStorage() {
let key: keyof Settings;

Expand Down Expand Up @@ -43,77 +45,81 @@ async function switchToSyncStorage() {
await store("switchedToSyncStorage", true);
}

async function clearUnusedStacks() {
const tabs = await browser.tabs.query({});
const tabIds = new Set(tabs.map((tab) => tab.id));
const stacksAvailable = await storageHas("hintsStacks");
const stacks = stacksAvailable ? await retrieve("hintsStacks") : new Map();

for (const [tabId] of stacks) {
if (!tabIds.has(tabId)) {
stacks.delete(tabId);
}
}

await store("hintsStacks", stacks);
async function resetHintsStacks() {
await store("hintsStacks", new Map());
}

export async function initBackgroundScript() {
const switchedToSyncStorage = await retrieve("switchedToSyncStorage");
if (!switchedToSyncStorage) await switchToSyncStorage();

await clearUnusedStacks();

let key: keyof typeof defaultSettings;
const storing: Array<Promise<void>> = [];

for (key in defaultSettings) {
if (Object.prototype.hasOwnProperty.call(defaultSettings, key)) {
storing.push(storeIfUndefined(key, defaultSettings[key]));
}
}
browser.runtime.onInstalled.addListener(
async ({ reason, previousVersion }) => {
if (reason !== "install" && reason !== "update") return;

await Promise.all(storing);
const switchedToSyncStorage = await retrieve("switchedToSyncStorage");
if (!switchedToSyncStorage) await switchToSyncStorage();

const keyboardClicking = await retrieve("keyboardClicking");
if (keyboardClicking) {
await (browser.action
? browser.action.setIcon({ path: urls.iconKeyboard48.pathname })
: browser.browserAction.setIcon({
path: urls.iconKeyboard48.pathname,
}));
}
let key: keyof typeof defaultSettings;
const storing: Array<Promise<void>> = [];

// We clean up the tabs in hintsToggleTabs on start
await store("hintsToggleTabs", new Map());
for (key in defaultSettings) {
if (Object.prototype.hasOwnProperty.call(defaultSettings, key)) {
storing.push(storeIfUndefined(key, defaultSettings[key]));
}
}

// Reset tabsByRecency on start
await store("tabsByRecency", {});
await Promise.all(storing);

if (
reason === "update" &&
(await retrieve("showWhatsNewPageOnUpdate")) &&
process.env["NODE_ENV"] === "production"
) {
const currentVersion = browser.runtime.getManifest().version;
const [currentMajor, currentMinor] = currentVersion.split(".") as [
string,
string,
string
];
const [previousMajor, previousMinor] = previousVersion!.split(".") as [
string,
string,
string
];

if (currentMajor !== previousMajor || currentMinor !== previousMinor) {
await browser.tabs.create({ url: urls.whatsNewPage.href });
}
}

// Track tabs to be able to use the command "tab back"
await trackRecentTabs();
await storeIfUndefined("hintsToggleTabs", new Map());
await storeIfUndefined("tabsByRecency", {});
// When updating we don't have to track the current tab as it's already
// being tracked
await trackRecentTabs(reason !== "update");

watchNavigation();
// If this is an update the content scrips either reload (Firefox) or stop
// completely (Chrome), either way we need to reset the hints stacks
await resetHintsStacks();

if (
(await retrieve("showWhatsNewPageOnUpdate")) &&
process.env["NODE_ENV"] === "production"
) {
const currentVersion = browser.runtime.getManifest().version;
const [currentMajor, currentMinor] = currentVersion.split(".") as [
string,
string,
string
];
watchNavigation();
}
);

browser.runtime.onStartup.addListener(async () => {
await resetHintsStacks();

const keyboardClicking = await retrieve("keyboardClicking");
if (keyboardClicking) {
await (browser.action
? browser.action.setIcon({ path: urls.iconKeyboard48.pathname })
: browser.browserAction.setIcon({
path: urls.iconKeyboard48.pathname,
}));
}

const lastWhatsNewPageShowed = await retrieve("lastWhatsNewPageShowed");
const [lastMajor, lastMinor] = lastWhatsNewPageShowed
? lastWhatsNewPageShowed.split(".")
: [undefined, undefined];
await store("hintsToggleTabs", new Map());
await store("tabsByRecency", {});
await trackRecentTabs(true);

if (currentMajor !== lastMajor || currentMinor !== lastMinor) {
await browser.tabs.create({ url: urls.whatsNewPage.href });
await store("lastWhatsNewPageShowed", currentVersion);
}
}
watchNavigation();
});
}
15 changes: 10 additions & 5 deletions src/background/setup/trackRecentTabs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,16 @@ async function updateRecentTab(
});
}

export async function trackRecentTabs() {
// We need to track the initial tab when the browser first opens
const currentTab = await getCurrentTab();
if (currentTab.windowId && currentTab.id) {
await updateRecentTab(currentTab.windowId, currentTab.id, false);
/**
* Start tracking tabs to be able to use the command `focusPreviousTab`.
*/
export async function trackRecentTabs(trackCurrentTab: boolean) {
if (trackCurrentTab) {
// We need to track the initial tab when the browser first opens
const currentTab = await getCurrentTab();
if (currentTab.windowId && currentTab.id) {
await updateRecentTab(currentTab.windowId, currentTab.id, false);
}
}

browser.tabs.onActivated.addListener(async (activeInfo) => {
Expand Down
1 change: 0 additions & 1 deletion src/typings/StorageSchema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,6 @@ export interface StorageSchema {
customSelectors: Record<string, CustomSelectors>;
switchedToSyncStorage: boolean;
showWhatsNewPageOnUpdate: boolean;
lastWhatsNewPageShowed?: string;
newTabPosition: "relatedAfterCurrent" | "afterCurrent" | "atEnd";

// Other data
Expand Down

0 comments on commit 1366881

Please sign in to comment.