WebExtensions Javascript Component Reference
This page contains reference documentation for the individual classes used to implement WebExtensions APIs. This documentation is generated from jsdoc comments in the source code.
ExtensionAPI class
- class ExtensionAPI()
Base class for WebExtension APIs. Each API creates a new class that inherits from this class, the derived class is instantiated once for each extension that uses the API.
- ExtensionAPI.ExtensionAPI
- ExtensionAPI.getAPI(_context)
- Arguments:
_context (BaseContext)
- ExtensionAPI.onManifestEntry(_entryName)
- Arguments:
_entryName (string)
- ExtensionAPI.onShutdown(_isAppShutdown)
- Arguments:
_isAppShutdown (boolean)
- static ExtensionAPI.onDisable(_id)
- Arguments:
_id (string)
- static ExtensionAPI.onUninstall(_id)
- Arguments:
_id (string)
- static ExtensionAPI.onUpdate(_id, _manifest)
- Arguments:
_id (string)
_manifest (object)
Extension class
- class Extension()
This class is the main representation of an active WebExtension in the main process.
- Extension.Extension
- Extension.activePermissions
Returns an object representing all capabilities this extension has access to, including fixed ones from the manifest as well as dynamically granted permissions.
- Extension.addonData
type: object
TODO: move to the Extension class, bug 1871094.
- Extension.backgroundState
backgroundState can be starting, running, suspending or stopped. It is undefined if the extension has no background page. See ext-backgroundPage.js for more details.
- Extension.baseURI
type: nsIURI
- Extension.manifestOptionalPermissions
Returns optional permissions from the manifest, including host permissions if originControls is true.
- Extension.persistentListeners
type: Map.<string, Map.<string, any>>
- Extension.principal
type: nsIPrincipal
- Extension.shortcuts
- Extension.tabManager
type: TabManagerBase
Extension’s TabManager, initialized at “startup” event of Management.
- Extension.temporarilyInstalled
type: boolean
- Extension.terminateBackground
- Extension.windowManager
type: WindowManagerBase
Extension’s WindowManager, initialized at “startup” event of Management.
- Extension._readDirectory(path, directoriesOnly=false)
Discovers the file names within a directory or JAR file.
- Arguments:
path (string) – The path to the directory or jar file to look at.
directoriesOnly (boolean) – If true, this will return only the directories present within the directory.
- Returns:
Promise.<Array.<string>> – An array of names of files/directories (only the name, not the path).
- Extension.callOnClose(obj)
Call the close() method on the given object when this extension is shut down. This can happen during browser shutdown, or when an extension is manually disabled or uninstalled.
- Arguments:
obj (object) – An object on which to call the close() method when this extension is shut down.
- Extension.clearCache(reason)
Clear cached resources associated to the extension principal when an extension is installed (in case we were unable to do that at uninstall time) or when it is being upgraded or downgraded.
- Arguments:
reason (string|undefined) – BOOTSTRAP_REASON string, if provided. The value is expected to be undefined for extension objects without a corresponding AddonManager addon wrapper (e.g. test extensions created using ExtensionTestUtils without useAddonManager optional property).
- Returns:
Promise.<void> – Promise resolved when the nsIClearDataService async method call has been completed.
- Extension.getLocalizedManifest(locale)
Load a locale and return a localized manifest. The extension must be initialized, and manifest parsed prior to calling.
- Arguments:
locale (string) – to load, if necessary.
- Returns:
Promise.<object> – normalized manifest.
- Extension.getManifestOrigins()
- Returns:
Array.<string> – all origins that are referenced in manifest via permissions, host_permissions, or content_scripts keys.
- Extension.getManifestOriginsMatchPatternSet()
- Returns:
MatchPatternSet – MatchPatternSet for only the origins that are referenced in manifest via permissions, host_permissions, or content_scripts keys.
- Extension.getRequestedPermissions()
Returns additional permissions that extensions is requesting based on its manifest. For now, this is host_permissions (and content scripts) in mv3.
- Extension.getRequiredPermissions()
Returns an object representing any capabilities that the extension has access to based on fixed properties in the manifest. The result includes the contents of the “permissions” property as well as other capabilities that are derived from manifest fields that users should be informed of (e.g., origins where content scripts are injected).
For MV3 extensions with origin controls, this does not include origins.
- Extension.getURL(path)
Returns the moz-extension: URL for the given path within this extension.
Must not be called unless either the id or uuid property has already been set.
- Arguments:
path (string) – The path portion of the URL.
- Returns:
string –
- Extension.manifestError(message)
Report an error about the extension’s manifest file.
- Arguments:
message (string) – The error message
- Extension.manifestWarning(message)
Report a warning about the extension’s manifest file.
- Arguments:
message (string) – The warning message
- Extension.permissionsObject(permissionsArray, hostPermissions)
Given an array of host and permissions, generate a structured permissions object that contains seperate host origins and permissions arrays.
- Arguments:
permissionsArray (Array)
hostPermissions (Array)
- Returns:
object – permissions object
- Extension.serializeExtended()
Extended serialized data which is only needed in the extensions process, and is never deserialized in web content processes. Keep in sync with @see {ExtensionChild}.
- Extension.updatePermissions(reason)
Update site permissions as necessary.
- Arguments:
reason (string) – If provided, this is a BOOTSTRAP_REASON string. If reason is undefined, addon permissions are being added or removed that may effect the site permissions.
EventManager class
- class EventManager(params)
This is a generic class for managing event listeners.
Examples:
new EventManager({ context, name: "api.subAPI", register: fire => { let listener = (...) => { // Fire any listeners registered with addListener. fire.async(arg1, arg2); }; // Register the listener. SomehowRegisterListener(listener); return () => { // Return a way to unregister the listener. SomehowUnregisterListener(listener); }; } }).api() The result is an object with addListener, removeListener, and hasListener methods. `context` is an add-on scope (either an ExtensionContext in the chrome process or ExtensionContext in a content process).
- static EventManager.clearPrimedListeners(extension, clearPersistent=true)
This is called as a result of background script startup-finished and shutdown.
After startup, it removes any remaining primed listeners. These exist if the listener was not renewed during startup. In this case the persisted listener data is also removed.
During shutdown, care should be taken to set clearPersistent to false. persisted listener data should NOT be cleared during shutdown.
- Arguments:
extension (Extension)
clearPersistent (boolean) – whether the persisted listener data should be cleared.
BaseContext class
- class BaseContext()
This class contains the information we have about an individual extension. It is never instantiated directly, instead subclasses for each type of process extend this class and add members that are relevant for that process.
- BaseContext.BaseContext
- BaseContext.cloneScope
type: object
- BaseContext.isTopContext
type: boolean
- BaseContext.principal
type: nsIPrincipal
- BaseContext.useWebIDLBindings
Whether the extension context is using the WebIDL bindings for the WebExtensions APIs. To be overridden in subclasses (e.g. WorkerContextChild) and to be optionally used in ExtensionAPI classes to customize the behavior of the API when the calls to the extension API are originated from the WebIDL bindings.
- BaseContext.viewType
type: string
- BaseContext.close()
A simple proxy for unload(), for use with callOnClose().
- BaseContext.getCaller()
Captures the most recent stack frame which belongs to the extension.
- Returns:
nsIStackFrame –
- BaseContext.jsonStringify(...args)
Safely call JSON.stringify() on an object that comes from an extension.
- Returns:
string – The stringified representation of obj
- BaseContext.normalizeError(error, caller)
Normalizes the given error object for use by the target scope. If the target is an error object which belongs to that scope, it is returned as-is. If it is an ordinary object with a message property, it is converted into an error belonging to the target scope. If it is an Error object which does not belong to the clone scope, it is reported, and converted to an unexpected exception error.
- Arguments:
error (Error|object)
caller (nsIStackFrame)
- Returns:
Error –
- BaseContext.openConduit(subject, address)
Opens a conduit linked to this context, populating related address fields. Only available in child contexts with an associated contentWindow.
- BaseContext.withLastError(error, caller, callback)
Sets the value of .lastError to error, calls the given callback, and reports an error if the value has not been checked when the callback returns.
- Arguments:
error (object) – An object with a message property. May optionally be an Error object belonging to the target scope.
caller (nsIStackFrame) – The optional caller frame which triggered this callback, to be used in error reporting.
callback (function) – The callback to call.
- Returns:
* – The return value of callback.
- BaseContext.wrapPromise(promise, callback=null)
Wraps the given promise so it can be safely returned to extension code in this context.
If callback is provided, however, it is used as a completion function for the promise, and no promise is returned. In this case, the callback is called when the promise resolves or rejects. In the latter case, lastError is set to the rejection value, and the callback function must check browser.runtime.lastError or extension.runtime.lastError in order to prevent it being reported to the console.
- Arguments:
promise (Promise) – The promise with which to wrap the callback. May resolve to a SpreadArgs instance, in which case each element will be used as a separate argument. Unless the promise object belongs to the cloneScope global, its resolution value is cloned into cloneScope prior to calling the callback function or resolving the wrapped promise.
callback (function) – The callback function to wrap
- Returns:
Promise|undefined – If callback is null, a promise object belonging to the target scope. Otherwise, undefined.
WindowManager class
- class WindowManagerBase(extension)
Manages native browser windows and their wrappers for a particular extension.
- Arguments:
extension (Extension) – The extension for which to manage windows.
- WindowManagerBase.canAccessWindow(window, context)
Returns whether this window can be accessed by the extension in the given context.
- Arguments:
window (DOMWindow) – The browser window that is being tested
context (BaseContext|null) – The extension context for which this test is being performed.
- Returns:
boolean –
- WindowManagerBase.convert(window, ...args)
Converts the given browser window to a JSON-compatible object, in the format required to be returned by WebExtension APIs, which may be safely passed to extension code.
- Arguments:
window (DOMWindow) – The browser window to convert.
args (*) – Additional arguments to be passed to {@link WindowBase#convert}.
- Returns:
object –
- WindowManagerBase.get(_windowId, _context)
Returns a WindowBase wrapper for the browser window with the given ID.
- Arguments:
_windowId (integer) – The ID of the browser window for which to return a wrapper.
_context (BaseContext) – The extension context for which the matching is being performed. Used to determine the current window for relevant properties.
- Throws:
ExtensionError – If no window exists with the given ID.
- Returns:
WindowBase –
- WindowManagerBase.getAll()
Returns an iterator of WindowBase wrappers for each currently existing browser window.
- Returns:
Iterator.<WindowBase> –
- WindowManagerBase.getWrapper(window)
Returns this extension’s WindowBase wrapper for the given browser window. This method will always return the same wrapper object for any given browser window.
- Arguments:
window (DOMWindow) – The browser window for which to return a wrapper.
- Returns:
WindowBase|undefined – The wrapper for this tab.
- WindowManagerBase.query(queryInfo=null, context=null)
Returns an iterator of WindowBase objects which match the given query info.
- Arguments:
queryInfo (object|null) – An object containing properties on which to filter. May contain any properties which are recognized by {@link WindowBase#matches}. Unknown properties will be ignored.
context (BaseContext|null) – The extension context for which the matching is being performed. Used to determine the current window for relevant properties.
- Returns:
Iterator.<WindowBase> –
- WindowManagerBase.wrapWindow(_window)
Returns a new WindowBase instance wrapping the given browser window.
- Arguments:
_window (DOMWindow) – The browser window for which to return a wrapper.
- Returns:
WindowBase –
TabManager class
- class TabManagerBase(extension)
Manages native tabs, their wrappers, and their dynamic permissions for a particular extension.
- Arguments:
extension (Extension) – The extension for which to manage tabs.
- TabManagerBase.activateScripts(nativeTab)
Activate MV3 content scripts if the extension has activeTab or an (ungranted) host permission.
- Arguments:
nativeTab (NativeTab)
- TabManagerBase.addActiveTabPermission(nativeTab)
If the extension has requested activeTab permission, grant it those permissions for the current inner window in the given native tab.
- Arguments:
nativeTab (NativeTab) – The native tab for which to grant permissions.
- TabManagerBase.canAccessTab(_nativeTab)
Determines access using extension context.
- Arguments:
_nativeTab (NativeTab) – The tab to check access on.
- Returns:
boolean – True if the extension has permissions for this tab.
- TabManagerBase.convert(nativeTab, fallbackTabSize=null)
Converts the given native tab to a JSON-compatible object, in the format required to be returned by WebExtension APIs, which may be safely passed to extension code.
- Arguments:
nativeTab (NativeTab) – The native tab to convert.
fallbackTabSize (object) – A geometry data if the lazy geometry data for this tab hasn’t been initialized yet.
- Returns:
object –
- TabManagerBase.get(_tabId)
Returns a TabBase wrapper for the tab with the given ID.
- Arguments:
_tabId (integer) – The ID of the tab for which to return a wrapper.
- Throws:
ExtensionError – If no tab exists with the given ID.
- Returns:
TabBase –
- TabManagerBase.getWrapper(nativeTab)
Returns this extension’s TabBase wrapper for the given native tab. This method will always return the same wrapper object for any given native tab.
- Arguments:
nativeTab (NativeTab) – The tab for which to return a wrapper.
- Returns:
TabBase|undefined – The wrapper for this tab.
- TabManagerBase.hasActiveTabPermission(nativeTab)
Returns true if the extension has requested activeTab permission, and has been granted permissions for the current inner window if this tab.
- Arguments:
nativeTab (NativeTab) – The native tab for which to check permissions.
- Returns:
boolean – True if the extension has activeTab permissions for this tab.
- TabManagerBase.hasTabPermission(nativeTab)
Returns true if the extension has permissions to access restricted properties of the given native tab. In practice, this means that it has either requested the “tabs” permission or has activeTab permissions for the given tab.
NOTE: Never use this method on an object that is not a native tab for the current platform: this method implicitly generates a wrapper for the passed nativeTab parameter and the platform-specific tabTracker instance is likely to store it in a map which is cleared only when the tab is closed (and so, if nativeTab is not a real native tab, it will never be cleared from the platform-specific tabTracker instance), See Bug 1458918 for a rationale.
- Arguments:
nativeTab (NativeTab) – The native tab for which to check permissions.
- Returns:
boolean – True if the extension has permissions for this tab.
- TabManagerBase.query(queryInfo=null, context=null)
Returns an iterator of TabBase objects which match the given query info.
- Arguments:
queryInfo (object|null) – An object containing properties on which to filter. May contain any properties which are recognized by {@link TabBase#matches} or {@link WindowBase#matches}. Unknown properties will be ignored.
context (BaseContext|null) – The extension context for which the matching is being performed. Used to determine the current window for relevant properties.
- Returns:
Iterator.<TabBase> –
- TabManagerBase.revokeActiveTabPermission(nativeTab)
Revoke the extension’s activeTab permissions for the current inner window of the given native tab.
- Arguments:
nativeTab (NativeTab) – The native tab for which to revoke permissions.
- TabManagerBase.wrapTab(_nativeTab)
Returns a new TabBase instance wrapping the given native tab.
- Arguments:
_nativeTab (NativeTab) – The native tab for which to return a wrapper.
- Returns:
TabBase –