Skip to content
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
17 changes: 1 addition & 16 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 1 addition & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,6 @@
"@sindresorhus/tsconfig": "^7.0.0",
"@types/chrome": "^0.0.307",
"@types/tape": "^5.8.1",
"@types/webextension-polyfill": "^0.12.2",
"buffer": "^6.0.3",
"eslint": "^8.57.0",
"eslint-config-pixiebrix": "^0.41.1",
Expand All @@ -52,8 +51,7 @@
"stream-browserify": "^3.0.0",
"tape": "^5.9.0",
"typescript": "^5.8.2",
"vitest": "^3.0.7",
"webextension-polyfill": "^0.12.0"
"vitest": "^3.0.7"
},
"targets": {
"main": false,
Expand Down
2 changes: 0 additions & 2 deletions source/logging.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
/* Warning: Do not use import browser-polyfill directly or indirectly */

// .bind preserves the call location in the console
const debug = console.debug.bind(console, "Messenger:");
const warn = console.warn.bind(console, "Messenger:");
Expand Down
20 changes: 14 additions & 6 deletions source/receiver.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import browser from "webextension-polyfill";
import { serializeError } from "serialize-error";
import { getContextName } from "webext-detect";

Expand All @@ -24,13 +23,13 @@
);
}

// MUST NOT be `async` or Promise-returning-only
function onMessageListener(
message: unknown,
sender: Sender,
): Promise<unknown> | undefined {
sendResponse: (response: unknown) => void,
): true | undefined {
if (!isMessengerMessage(message)) {
// TODO: Add test for this eventuality: ignore unrelated messages

Check warning on line 32 in source/receiver.ts

View workflow job for this annotation

GitHub Actions / Lint

Unexpected 'todo' comment: 'TODO: Add test for this eventuality:...'

Check warning on line 32 in source/receiver.ts

View workflow job for this annotation

GitHub Actions / Lint

Unexpected 'todo' comment: 'TODO: Add test for this eventuality:...'
return;
}

Expand All @@ -45,7 +44,17 @@
return;
}

return handleMessage(message, sender, action);
(async () => {
try {
sendResponse(await handleMessage(message, sender, action));
} catch (error) {
sendResponse({ __webextMessenger: true, error: serializeError(error) });
}
})();

// Make `sendMessage` wait for an async response. This stops other `onMessage` listeners from being called.
// TODO: Just return a promise if this is ever implemented https://issues.chromium.org/issues/40753031

Check warning on line 56 in source/receiver.ts

View workflow job for this annotation

GitHub Actions / Lint

Unexpected 'todo' comment: 'TODO: Just return a promise if this is...'

Check warning on line 56 in source/receiver.ts

View workflow job for this annotation

GitHub Actions / Lint

Unexpected 'todo' comment: 'TODO: Just return a promise if this is...'
return true;
}

// This function can only be called when the message *will* be handled locally.
Expand Down Expand Up @@ -78,7 +87,7 @@
const localHandler = handlers.get(type);
if (!localHandler) {
if (!didUserRegisterMethods()) {
// TODO: Test the handling of __getTabData in contexts that have no registered methods

Check warning on line 90 in source/receiver.ts

View workflow job for this annotation

GitHub Actions / Lint

Unexpected 'todo' comment: 'TODO: Test the handling of __getTabData...'

Check warning on line 90 in source/receiver.ts

View workflow job for this annotation

GitHub Actions / Lint

Unexpected 'todo' comment: 'TODO: Test the handling of __getTabData...'
// https://github.com/pixiebrix/webext-messenger/pull/82
throw new MessengerError(
`No handlers registered in ${getContextName()}`,
Expand All @@ -97,7 +106,6 @@
(value) => ({ value }),
(error: unknown) => ({
// Errors must be serialized because the stack traces are currently lost on Chrome
// and https://github.com/mozilla/webextension-polyfill/issues/210
error: serializeError(error),
}),
);
Expand All @@ -116,7 +124,7 @@
handlers.set(type, method as Method);
}

browser.runtime.onMessage.addListener(onMessageListener);
chrome.runtime.onMessage.addListener(onMessageListener);
}

/** Ensure/document that the current function was called via Messenger */
Expand Down
14 changes: 6 additions & 8 deletions source/sender.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import browser from "webextension-polyfill";
import pRetry from "p-retry";
import { isBackground } from "webext-detect";
import { deserializeError } from "serialize-error";
Expand All @@ -22,7 +21,6 @@
const _errorNonExistingTarget =
"Could not establish connection. Receiving end does not exist.";

// https://github.com/mozilla/webextension-polyfill/issues/384
const _errorTargetClosedEarly =
"A listener indicated an asynchronous response by returning true, but the message channel closed before a response was received";

Expand Down Expand Up @@ -74,14 +72,14 @@
});
}

async function manageMessage(

Check warning on line 75 in source/sender.ts

View workflow job for this annotation

GitHub Actions / Lint

Async function 'manageMessage' has too many parameters (5). Maximum allowed is 4

Check warning on line 75 in source/sender.ts

View workflow job for this annotation

GitHub Actions / Lint

Async function 'manageMessage' has too many parameters (5). Maximum allowed is 4
type: string,
target: AnyTarget,
seq: number,
retry: boolean,
sendMessage: (attempt: number) => Promise<unknown>,
): Promise<unknown> {
// TODO: Split this up a bit because it's too long. Probably drop p-retry

Check warning on line 82 in source/sender.ts

View workflow job for this annotation

GitHub Actions / Lint

Unexpected 'todo' comment: 'TODO: Split this up a bit because it's...'

Check warning on line 82 in source/sender.ts

View workflow job for this annotation

GitHub Actions / Lint

Unexpected 'todo' comment: 'TODO: Split this up a bit because it's...'
const response = await pRetry(
async (attemptCount) => {
const response = await sendMessage(attemptCount);
Expand Down Expand Up @@ -166,9 +164,9 @@
throw error;
}

if (browser.tabs && typeof target.tabId === "number") {
if (chrome.tabs && typeof target.tabId === "number") {
try {
const tabInfo = await browser.tabs.get(target.tabId);
const tabInfo = await chrome.tabs.get(target.tabId);
if (tabInfo.discarded) {
throw new Error(errorTabWasDiscarded);
}
Expand Down Expand Up @@ -270,7 +268,7 @@
"↗️ sending message to runtime",
attemptLog(attemptCount),
);
return browser.runtime.sendMessage(
return chrome.runtime.sendMessage(
makeMessage(type, args, target, options),
);
};
Expand All @@ -279,7 +277,7 @@
}

// Contexts without direct Tab access must go through background
if (!browser.tabs) {
if (!chrome.tabs) {
return manageConnection(
type,
options,
Expand All @@ -291,7 +289,7 @@
"↗️ sending message to runtime",
attemptLog(attemptCount),
);
return browser.runtime.sendMessage(
return chrome.runtime.sendMessage(
makeMessage(type, args, target, options),
);
},
Expand All @@ -316,7 +314,7 @@
frameId,
attemptLog(attemptCount),
);
return browser.tabs.sendMessage(
return chrome.tabs.sendMessage(
tabId,
makeMessage(type, args, target, options),
frameId === "allFrames"
Expand Down
8 changes: 6 additions & 2 deletions source/targetLogic.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { assert, describe, test, vi } from "vitest";
import { getActionForMessage } from "./targetLogic.js";
import { type Tabs } from "webextension-polyfill";
import { isContentScript, isBackground } from "webext-detect";

vi.mock("webext-detect");
Expand All @@ -14,7 +13,12 @@ const tab = {
pinned: false,
highlighted: true,
incognito: false,
} satisfies Tabs.Tab;
discarded: false,
frozen: false,
selected: true,
autoDiscardable: false,
groupId: -1,
} satisfies chrome.tabs.Tab;

const senders = {
background: { page: "background" },
Expand Down
13 changes: 6 additions & 7 deletions source/test/background/testingApi.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import browser from "webextension-polyfill";
import { once } from "webext-messenger/shared.js";

export async function ensureScripts(tabId: number): Promise<void> {
await browser.scripting.executeScript({
await chrome.scripting.executeScript({
target: { tabId },
files: ["contentscript/registration.js"],
});
Expand Down Expand Up @@ -34,7 +33,7 @@ export async function createTargets(): Promise<Targets> {
let frames;
while (limit--) {
// eslint-disable-next-line no-await-in-loop -- It's a retry loop
frames = (await browser.webNavigation.getAllFrames({
frames = (await chrome.webNavigation.getAllFrames({
tabId,
}))!;

Expand All @@ -60,15 +59,15 @@ export async function createTargets(): Promise<Targets> {
}

const getHiddenWindow = once(async (): Promise<number> => {
const { id } = await browser.windows.create({
const { id } = await chrome.windows.create({
focused: false,
state: "minimized",
});
return id!;
});

export async function openTab(url: string): Promise<number> {
const tab = await browser.tabs.create({
const tab = await chrome.tabs.create({
windowId: await getHiddenWindow(),
active: false,
url,
Expand All @@ -77,9 +76,9 @@ export async function openTab(url: string): Promise<number> {
}

export async function closeHiddenWindow(): Promise<void> {
return browser.windows.remove(await getHiddenWindow());
return chrome.windows.remove(await getHiddenWindow());
}

export async function closeTab(tabId: number): Promise<void> {
await browser.tabs.remove(tabId);
await chrome.tabs.remove(tabId);
}
3 changes: 1 addition & 2 deletions source/test/contentscript/api.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import browser from "webextension-polyfill";
import test from "tape";
import { isBackground, isContentScript, isWebPage } from "webext-detect";
import { type PageTarget, type Target } from "webext-messenger";
Expand Down Expand Up @@ -184,7 +183,7 @@ async function testEveryTarget() {
await closeSelf({ tabId, frameId: parentFrame });
try {
// Since the tab was closed, this is expected to throw
t.notOk(await browser.tabs.get(tabId), "The tab should not be open");
t.notOk(await chrome.tabs.get(tabId), "The tab should not be open");
} catch {
t.pass("The tab was closed");
}
Expand Down
11 changes: 6 additions & 5 deletions source/test/contentscript/fixtures/unrelatedMessageListener.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
import browser from "webextension-polyfill";

browser.runtime.onMessage.addListener(
(message: unknown): Promise<string> | undefined => {
chrome.runtime.onMessage.addListener(
(message: unknown, _sender, sendResponse): boolean | undefined => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
if ((message as any)?.type === "sleep") {
console.log(
"I’m an unrelated message listener, but I'm replying anyway to",
{ message },
);
return Promise.resolve("/r/nosleep");

void Promise.resolve("Buonanotte").then(sendResponse);

return true;
}

console.log("I’m an unrelated message listener. I’ve seen", { message });
Expand Down
3 changes: 1 addition & 2 deletions source/types.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { type Runtime } from "webextension-polyfill";
import { type Asyncify, type ValueOf } from "type-fest";
import { type ErrorObject } from "serialize-error";

Expand Down Expand Up @@ -83,7 +82,7 @@ export type Message<LocalArguments extends Arguments = Arguments> = {
options?: Options;
};

export type Sender = Runtime.MessageSender & { origin?: string }; // Chrome includes the origin
export type Sender = chrome.runtime.MessageSender;

export type MessengerMessage = Message & {
/** Guarantees that a message is meant to be handled by this library */
Expand Down
Loading