Skip to content

Commit

Permalink
Only forward messages in the background page (#224)
Browse files Browse the repository at this point in the history
  • Loading branch information
fregante authored Mar 21, 2024
1 parent fc13d75 commit f5d2ebe
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 4 deletions.
5 changes: 3 additions & 2 deletions source/targetLogic.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { assert, describe, test, vi } from "vitest";
import { getActionForMessage } from "./targetLogic.js";
import { type Tabs } from "webextension-polyfill";
import { isContentScript } from "webext-detect-page";
import { isContentScript, isBackground } from "webext-detect-page";

vi.mock("webext-detect-page");

Expand Down Expand Up @@ -55,7 +55,7 @@ describe("getActionForMessage", async () => {
["contentScript", "somePage", "frame", "respond"], // Wrong, but won't happen

["contentScript", "thisTab", "background", "forward"],
["contentScript", "thisTab", "somePage", "forward"],
["contentScript", "thisTab", "somePage", "ignore"],
["contentScript", "thisTab", "tab", "respond"], // Won't happen, content scripts cannot target tabs
["contentScript", "thisTab", "frame", "respond"], // Won't happen, content scripts cannot target tabs
] satisfies Array<
Expand All @@ -70,6 +70,7 @@ describe("getActionForMessage", async () => {
async (from, to, receiver, expected) => {
const isCs = receiver === "tab" || receiver === "frame";
vi.mocked(isContentScript).mockReturnValueOnce(isCs);
vi.mocked(isBackground).mockReturnValueOnce(receiver === "background");
vi.stubGlobal("location", {
origin: isCs ? "http://example.com" : "chrome-extension://extension-id",
});
Expand Down
9 changes: 7 additions & 2 deletions source/targetLogic.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { isContentScript } from "webext-detect-page";
import { isBackground, isContentScript } from "webext-detect-page";
import { type AnyTarget, type Sender } from "./types.js";
import { type Entries } from "type-fest";

Expand Down Expand Up @@ -47,7 +47,12 @@ export function getActionForMessage(

// We're in an extension page, but the target is not one.
if (!to.page) {
return "forward";
// Only the background page can forward messages at the moment
// https://github.com/pixiebrix/webext-messenger/issues/219#issuecomment-2011000477
// If this condition is changed, it might also need to ensure that messages are not
// forwarded to itself, e.g. when using the tabs API in an iframed extension page.
// https://github.com/pixiebrix/webext-messenger/issues/221#issuecomment-2010165690
return isBackground() ? "forward" : "ignore";
}

// Set "this" tab to the current tabId
Expand Down

0 comments on commit f5d2ebe

Please sign in to comment.