Skip to content

Commit

Permalink
fix(context): Deduplicate wxt:content-script-started (#1364)
Browse files Browse the repository at this point in the history
Co-authored-by: DenizUgur <[email protected]>
Co-authored-by: Aaron <[email protected]>
  • Loading branch information
3 people authored Jan 28, 2025
1 parent 665b919 commit a53ee6d
Showing 1 changed file with 14 additions and 4 deletions.
18 changes: 14 additions & 4 deletions packages/wxt/src/client/content-scripts/content-script-context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ export class ContentScriptContext implements AbortController {
private isTopFrame = window.self === window.top;
private abortController: AbortController;
private locationWatcher = createLocationWatcher(this);
private receivedMessageIds = new Set<string>();

constructor(
private readonly contentScriptName: string,
Expand Down Expand Up @@ -233,19 +234,28 @@ export class ContentScriptContext implements AbortController {
{
type: ContentScriptContext.SCRIPT_STARTED_MESSAGE_TYPE,
contentScriptName: this.contentScriptName,
messageId: Math.random().toString(36).slice(2),
},
'*',
);
}

verifyScriptStartedEvent(event: MessageEvent) {
const isScriptStartedEvent =
event.data?.type === ContentScriptContext.SCRIPT_STARTED_MESSAGE_TYPE;
const isSameContentScript =
event.data?.contentScriptName === this.contentScriptName;
const isNotDuplicate = !this.receivedMessageIds.has(event.data?.messageId);
return isScriptStartedEvent && isSameContentScript && isNotDuplicate;
}

listenForNewerScripts(options?: { ignoreFirstEvent?: boolean }) {
let isFirst = true;

const cb = (event: MessageEvent) => {
if (
event.data?.type === ContentScriptContext.SCRIPT_STARTED_MESSAGE_TYPE &&
event.data?.contentScriptName === this.contentScriptName
) {
if (this.verifyScriptStartedEvent(event)) {
this.receivedMessageIds.add(event.data.messageId);

const wasFirst = isFirst;
isFirst = false;
if (wasFirst && options?.ignoreFirstEvent) return;
Expand Down

0 comments on commit a53ee6d

Please sign in to comment.