Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix background script set up running every time the background script/service worker is restarted #133

Merged
merged 1 commit into from
Jun 6, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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