API > wxt/utils/content-script-context > ContentScriptContext
Class: ContentScriptContext
Implements 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:
import { ContentScriptContext } from 'wxt/utils/content-scripts-context';
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);
});Contents
Implements
AbortController
Constructors
new ContentScriptContext(contentScriptName, options)
new ContentScriptContext(
contentScriptName,options?):ContentScriptContext
Parameters
▪ contentScriptName: string
▪ options?: Omit<ContentScriptDefinition, "main">
Source
packages/wxt/src/utils/content-script-context.ts:51
Properties
abortController
privateabortController:AbortController
Source
packages/wxt/src/utils/content-script-context.ts:47
contentScriptName
privatereadonlycontentScriptName:string
Source
packages/wxt/src/utils/content-script-context.ts:52
isTopFrame
privateisTopFrame:boolean
Source
packages/wxt/src/utils/content-script-context.ts:46
locationWatcher
privatelocationWatcher:object
Type declaration
run()
Ensure the location watcher is actively looking for URL changes. If it's already watching, this is a noop.
Source
packages/wxt/src/utils/content-script-context.ts:48
options
readonlyoptions?:Omit<ContentScriptDefinition,"main">
Source
packages/wxt/src/utils/content-script-context.ts:53
receivedMessageIds
privatereceivedMessageIds:Set<string>
Source
packages/wxt/src/utils/content-script-context.ts:49
SCRIPT_STARTED_MESSAGE_TYPE
privatestaticSCRIPT_STARTED_MESSAGE_TYPE:string
Source
packages/wxt/src/utils/content-script-context.ts:42
Accessors
isInvalid
getisInvalid():boolean
Source
packages/wxt/src/utils/content-script-context.ts:73
isValid
getisValid():boolean
Source
packages/wxt/src/utils/content-script-context.ts:80
signal
getsignal():AbortSignal
Source
packages/wxt/src/utils/content-script-context.ts:65
Methods
abort()
abort(
reason?):void
Parameters
▪ reason?: any
Implementation of
AbortController.abort
Source
packages/wxt/src/utils/content-script-context.ts:69
addEventListener()
addEventListener(target, type, handler, options)
addEventListener<
TType>(target,type,handler,options?):void
Call target.addEventListener and remove the event listener when the context is invalidated.
Listeners can be canceled by calling the normal removeEventListener function.
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.
Type parameters
▪ TType extends keyof WxtWindowEventMap
Parameters
▪ target: Window
▪ type: TType
▪ handler: (event) => void
▪ options?: AddEventListenerOptions
Returns
Example
ctx.addEventListener(document, "visibilitychange", () => {
// ...
});
ctx.addEventListener(window, "wxt:locationchange", () => {
// ...
});Source
packages/wxt/src/utils/content-script-context.ts:197
addEventListener(target, type, handler, options)
addEventListener<
TType>(target,type,handler,options?):void
Type parameters
▪ TType extends keyof DocumentEventMap
Parameters
▪ target: Document
▪ type: TType
▪ handler: (event) => void
▪ options?: AddEventListenerOptions
Source
packages/wxt/src/utils/content-script-context.ts:203
addEventListener(target, params)
addEventListener<
TTarget>(target, ...params):void
Type parameters
▪ TTarget extends EventTarget
Parameters
▪ target: TTarget
▪ ...params: Parameters<TTarget["addEventListener"]>
Source
packages/wxt/src/utils/content-script-context.ts:209
block()
block<
T>():Promise<T>
Return a promise that never resolves. Useful if you have an async function that shouldn't run after the context is expired.
Type parameters
▪ T
Returns
Example
const getValueFromStorage = async () => {
if (ctx.isInvalid) return ctx.block();
// ...
}Source
packages/wxt/src/utils/content-script-context.ts:113
listenForNewerScripts()
listenForNewerScripts(
options?):void
Parameters
▪ options?: object
▪ options.ignoreFirstEvent?: boolean
Source
packages/wxt/src/utils/content-script-context.ts:266
notifyInvalidated()
notifyInvalidated():
void
Abort the abort controller and execute all onInvalidated listeners.
Source
packages/wxt/src/utils/content-script-context.ts:238
onInvalidated()
onInvalidated(
cb): () =>void
Add a listener that is called when the content script's context is invalidated.
Parameters
▪ cb: () => void
Returns
A function to remove the listener.
():
voidSource
Example
browser.runtime.onMessage.addListener(cb);
const removeInvalidatedListener = ctx.onInvalidated(() => {
browser.runtime.onMessage.removeListener(cb);
})
// ...
removeInvalidatedListener();Source
packages/wxt/src/utils/content-script-context.ts:97
requestAnimationFrame()
requestAnimationFrame(
callback):number
Wrapper around window.requestAnimationFrame that automatically cancels the request when invalidated.
Callbacks can be canceled by calling the normal cancelAnimationFrame function.
Parameters
▪ callback: FrameRequestCallback
Source
packages/wxt/src/utils/content-script-context.ts:151
requestIdleCallback()
requestIdleCallback(
callback,options?):number
Wrapper around window.requestIdleCallback that automatically cancels the request when invalidated.
Callbacks can be canceled by calling the normal cancelIdleCallback function.
Parameters
▪ callback: IdleRequestCallback
▪ options?: IdleRequestOptions
Source
packages/wxt/src/utils/content-script-context.ts:166
setInterval()
setInterval(
handler,timeout?):number
Wrapper around window.setInterval that automatically clears the interval when invalidated.
Intervals can be cleared by calling the normal clearInterval function.
Parameters
▪ handler: () => void
▪ timeout?: number
Source
packages/wxt/src/utils/content-script-context.ts:124
setTimeout()
setTimeout(
handler,timeout?):number
Wrapper around window.setTimeout that automatically clears the interval when invalidated.
Timeouts can be cleared by calling the normal setTimeout function.
Parameters
▪ handler: () => void
▪ timeout?: number
Source
packages/wxt/src/utils/content-script-context.ts:137
stopOldScripts()
stopOldScripts():
void
Source
packages/wxt/src/utils/content-script-context.ts:245
verifyScriptStartedEvent()
verifyScriptStartedEvent(
event):boolean
Parameters
▪ event: MessageEvent<any>
Source
packages/wxt/src/utils/content-script-context.ts:257
Generated using typedoc-plugin-markdown and TypeDoc