Skip to content

Commit

Permalink
feat(web-extension): detect bg script when on firefox
Browse files Browse the repository at this point in the history
Firefox runs background script in a hidden page,
so it has a window object.
  • Loading branch information
mirceahasegan committed Feb 3, 2025
1 parent b13c33d commit 3a260ee
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 2 deletions.
5 changes: 3 additions & 2 deletions packages/web-extension/src/messaging/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { BackgroundMessenger, createBackgroundMessenger, generalizeBackgroundMessenger } from './BackgroundMessenger';
import { ChannelName, ConsumeRemoteApiOptions, ExposeApiProps, MessengerDependencies } from './types';
import { FinalizationRegistryDestructor } from './util';
import { FinalizationRegistryDestructor, isBackgroundProcess } from './util';
import { consumeMessengerRemoteApi, exposeMessengerApi } from './remoteApi';
import { createNonBackgroundMessenger } from './NonBackgroundMessenger';
import { runtime } from 'webextension-polyfill';

export * from './BackgroundMessenger';
export * from './NonBackgroundMessenger';
Expand All @@ -15,7 +16,7 @@ export * from './errors';

export type BaseChannel = { baseChannel: ChannelName };

const isInBackgroundProcess = typeof window === 'undefined';
const isInBackgroundProcess = isBackgroundProcess(runtime);

const getBackgroundMessenger = (() => {
let backgroundMessenger: BackgroundMessenger | null = null;
Expand Down
1 change: 1 addition & 0 deletions packages/web-extension/src/messaging/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ export interface MessengerPort {
export interface MinimalRuntime {
connect(connectInfo: Runtime.ConnectConnectInfoType): MessengerPort;
onConnect: MinimalEvent<(port: MessengerPort) => void>;
getBackgroundPage?: unknown;
lastError?: unknown;
}

Expand Down
4 changes: 4 additions & 0 deletions packages/web-extension/src/messaging/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
FactoryCallMessage,
InternalMsg,
MethodRequest,
MinimalRuntime,
RequestMessage,
ResponseMessage
} from './types';
Expand Down Expand Up @@ -77,3 +78,6 @@ export class FinalizationRegistryDestructor implements Destructor {
this.#registry.register(obj, objectId);
}
}

export const isBackgroundProcess = (runtime: MinimalRuntime) =>
typeof window === 'undefined' || typeof runtime.getBackgroundPage === 'function';

0 comments on commit 3a260ee

Please sign in to comment.