-
-
Notifications
You must be signed in to change notification settings - Fork 272
/
Copy pathcontent-script-context.ts
306 lines (275 loc) · 8.74 KB
/
content-script-context.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
import { browser } from 'wxt/browser';
import { logger } from '../../sandbox/utils/logger';
import { ContentScriptDefinition } from '../../types';
import { WxtLocationChangeEvent, getUniqueEventName } from './custom-events';
import { createLocationWatcher } from './location-watcher';
/**
* Implements [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController).
* Used to detect and stop content script code when the script is invalidated.
*
* It also provides several utilities like `ctx.setTimeout` and `ctx.setInterval` that should be used in
* content scripts instead of `window.setTimeout` or `window.setInterval`.
*
* To create context for testing, you can use the class's constructor:
*
* ```ts
* import { ContentScriptContext } from 'wxt/client';
*
* test("storage listener should be removed when context is invalidated", () => {
* const ctx = new ContentScriptContext('test');
* const item = storage.defineItem("local:count", { defaultValue: 0 });
* const watcher = vi.fn();
*
* const unwatch = item.watch(watcher);
* ctx.onInvalidated(unwatch); // Listen for invalidate here
*
* await item.setValue(1);
* expect(watcher).toBeCalledTimes(1);
* expect(watcher).toBeCalledWith(1, 0);
*
* ctx.notifyInvalidated(); // Use this function to invalidate the context
* await item.setValue(2);
* expect(watcher).toBeCalledTimes(1);
* });
* ```
*/
export class ContentScriptContext implements AbortController {
private static SCRIPT_STARTED_MESSAGE_TYPE = getUniqueEventName(
'wxt:content-script-started',
);
private isTopFrame = window.self === window.top;
private abortController: AbortController;
private locationWatcher = createLocationWatcher(this);
private receivedMessageIds = new Set<string>();
constructor(
private readonly contentScriptName: string,
public readonly options?: Omit<ContentScriptDefinition, 'main'>,
) {
this.abortController = new AbortController();
if (this.isTopFrame) {
this.listenForNewerScripts({ ignoreFirstEvent: true });
this.stopOldScripts();
} else {
this.listenForNewerScripts();
}
}
get signal() {
return this.abortController.signal;
}
abort(reason?: any): void {
return this.abortController.abort(reason);
}
get isInvalid(): boolean {
if (browser.runtime.id == null) {
this.notifyInvalidated(); // Sets `signal.aborted` to true
}
return this.signal.aborted;
}
get isValid(): boolean {
return !this.isInvalid;
}
/**
* Add a listener that is called when the content script's context is invalidated.
*
* @returns A function to remove the listener.
*
* @example
* browser.runtime.onMessage.addListener(cb);
* const removeInvalidatedListener = ctx.onInvalidated(() => {
* browser.runtime.onMessage.removeListener(cb);
* })
* // ...
* removeInvalidatedListener();
*/
onInvalidated(cb: () => void): () => void {
this.signal.addEventListener('abort', cb);
return () => this.signal.removeEventListener('abort', cb);
}
/**
* Return a promise that never resolves. Useful if you have an async function that shouldn't run
* after the context is expired.
*
* @example
* const getValueFromStorage = async () => {
* if (ctx.isInvalid) return ctx.block();
*
* // ...
* }
*/
block<T>(): Promise<T> {
return new Promise(() => {
// noop
});
}
/**
* Wrapper around `window.setInterval` that automatically clears the interval when invalidated.
*/
setInterval(handler: () => void, timeout?: number): number {
const id = setInterval(() => {
if (this.isValid) handler();
}, timeout) as unknown as number;
this.onInvalidated(() => clearInterval(id));
return id;
}
/**
* Wrapper around `window.setTimeout` that automatically clears the interval when invalidated.
*/
setTimeout(handler: () => void, timeout?: number): number {
const id = setTimeout(() => {
if (this.isValid) handler();
}, timeout) as unknown as number;
this.onInvalidated(() => clearTimeout(id));
return id;
}
/**
* Wrapper around `window.requestAnimationFrame` that automatically cancels the request when
* invalidated.
*/
requestAnimationFrame(callback: FrameRequestCallback): number {
const id = requestAnimationFrame((...args) => {
if (this.isValid) callback(...args);
});
this.onInvalidated(() => cancelAnimationFrame(id));
return id;
}
/**
* Wrapper around `window.requestIdleCallback` that automatically cancels the request when
* invalidated.
*/
requestIdleCallback(
callback: IdleRequestCallback,
options?: IdleRequestOptions,
): number {
const id = requestIdleCallback((...args) => {
if (!this.signal.aborted) callback(...args);
}, options);
this.onInvalidated(() => cancelIdleCallback(id));
return id;
}
/**
* Clears a timeout set by ctx.setTimeout.
*/
clearTimeout(id: number | null): void {
if (id !== null) {
clearTimeout(id);
}
}
/**
* Clears an interval set by ctx.setInterval.
*/
clearInterval(id: number | null): void {
if (id !== null) {
clearInterval(id);
}
}
/**
* Cancels an animation frame request set by ctx.requestAnimationFrame.
*/
cancelAnimationFrame(id: number): void {
cancelAnimationFrame(id);
}
/**
* Cancels an idle callback request set by ctx.requestIdleCallback.
*/
cancelIdleCallback(id: number): void {
cancelIdleCallback(id);
}
/**
* Call `target.addEventListener` and remove the event listener when the context is invalidated.
*
* Includes additional events useful for content scripts:
*
* - `"wxt:locationchange"` - Triggered when HTML5 history mode is used to change URL. Content
* scripts are not reloaded when navigating this way, so this can be used to reset the content
* script state on URL change, or run custom code.
*
* @example
* ctx.addEventListener(document, "visibilitychange", () => {
* // ...
* });
* ctx.addEventListener(window, "wxt:locationchange", () => {
* // ...
* });
*/
addEventListener<TType extends keyof WxtWindowEventMap>(
target: Window,
type: TType,
handler: (event: WxtWindowEventMap[TType]) => void,
options?: AddEventListenerOptions,
): void;
addEventListener<TType extends keyof DocumentEventMap>(
target: Document,
type: keyof DocumentEventMap,
handler: (event: DocumentEventMap[TType]) => void,
options?: AddEventListenerOptions,
): void;
addEventListener<TTarget extends EventTarget>(
target: TTarget,
...params: Parameters<TTarget['addEventListener']>
): void;
addEventListener(
target: EventTarget,
type: string,
handler: (event: Event) => void,
options?: AddEventListenerOptions,
): void {
if (type === 'wxt:locationchange') {
// Start the location watcher when adding the event for the first time
if (this.isValid) this.locationWatcher.run();
}
target.addEventListener?.(
type.startsWith('wxt:') ? getUniqueEventName(type) : type,
handler,
{
...options,
signal: this.signal,
},
);
}
/**
* @internal
* Abort the abort controller and execute all `onInvalidated` listeners.
*/
notifyInvalidated() {
this.abort('Content script context invalidated');
logger.debug(
`Content script "${this.contentScriptName}" context invalidated`,
);
}
stopOldScripts() {
// Use postMessage so it get's sent to all the frames of the page.
window.postMessage(
{
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 (this.verifyScriptStartedEvent(event)) {
this.receivedMessageIds.add(event.data.messageId);
const wasFirst = isFirst;
isFirst = false;
if (wasFirst && options?.ignoreFirstEvent) return;
this.notifyInvalidated();
}
};
addEventListener('message', cb);
this.onInvalidated(() => removeEventListener('message', cb));
}
}
export interface WxtWindowEventMap extends WindowEventMap {
'wxt:locationchange': WxtLocationChangeEvent;
}