Modern browsers can add new functionality to sites and the browser itself through script-based extensions. This document specifies an API set that allows developers to create interoperable extensions for browsers that support the API set, as well as the packaging format to be used for such extensions.

This specification is not actively maintained. Issues previously filed against it can be read on github. A public archived mailing list was also available, but was reserved for high level discussions, and was not appropriate for specific comments about this document.

Work on this document is governed by the charter of the Browser Extension CG, which includes among other things the Communication, Decision, and Contribution policies of this community group.

Implementation of the technologies discussed and tentatively specified in this Community Group is ongoing and none of the original contributors have expressed opposition to this work. However, due to various circumstances, the level of participation has dropped below the level at which productive discussion is possible, and activity in this group has stopped as a result.

The specifications have therefore not been maintained in a while, and are out of date.

In the meanwhile, a new “WebExtensions Community Group”, with similar objectives but much more active participation, has sprung up. People interested in this topic are encouraged to join that group.

Introduction

Because browsers supported different add-on models, extension authors wound up creating divergent codebases and delivering different browser-specific add-ons. This Community Group's goal is to make browser extension code much more interoperable across browsers by specifying common extension interfaces and well-defined browser behavior. This will allow extension authors to greatly reduce or eliminate the rework necessary to create extensions that target different browsers.

Core APIs

The goal for these core APIs is to provide functionality that extension authors need for:

Need to resolve ID issue before we can address messaging ('passing data')
GitHub Issues 14 & 17

API Availability

Overview

Browser extensions are authored primarily with JavaScript. In addition to the usual JavaScript Web APIs, additional APIs are available exclusively to extensions via the browser object. However, the specific APIs that are available to an extension from the browser object are dependent upon:

  • Execution context (e.g. background/event, popup, options, content, extension page)
  • Keys declared in the manifest (e.g. browser_action, page_action)
  • Permissions declared in the manifest (e.g. contextMenu, tabs, webNavigation, webRequest)
  • Content Security Policy (CSP) for the extension and target web page (for content scripts)

Execution Context and Manifest Restrictions

Browser extension pages and their corresponding scripts are executed in one of the following contexts. The manifest declarations required to create each specific type of page are described below.

  • Browser extension contexts ("Window") - Most extension APIs are available to this context
    • Background page - use the "background" manifest key and specify "persistent" true
    • Event page - use the "background" manifest key and specify "persistent" false
    • Popup page - use the "browser_action" or "page_action" manifest key and specify "default_popup"
    • Options page - use the "options_page" manifest key
    • Custom page - such as "browserext://<ext_id>/myCustomPage.html"
  • Content script context - A limited number of APIs are available to script that extensions use to interact with hosted web site pages
  • Internet-hosted web page context - Messaging APIs can be used to send messages from hosted web site pages such as https://en.wikipedia.org/wiki/Main_Page/index.html or https://w3c.github.io/html/index.html to extensions
Table: API Availability Summary

Some browser extension API require a specific manifest key or specific permission. If the key or permission are not declared or not granted, the object will not be available for scripting. These requirements are summarized in the table below. If manifest keys that are not defined in this specification are specified, other browsers MAY elect to ignore those additional keys.

API object Execution Context Required Declaration
Background page,Event page,Popup page,Options page,Custom page Content script page Internet-hosted web page Manifest key
browserAction Y1

"browser_action"1
contextMenus Y

"permissions":["context_menus"]
extension Y Y

i18n Y Y

"default_lang" : "<lang>"4
pageAction Y1

"page_action"1
runtime Y Y Y3 “externally_connectable”:[...] 2
tabs Y

"permissions":["tabs","activeTab"]
webNavigation Y

"permissions":["webNavigation"]
webRequest Y

"permissions":["webRequest"]
windows Y

1 Either browserAction or pageAction is allowed at the same time, not both
2The runtime object is available for use by extensions without declaring "externally_connectable" in the manifest. However, an extension will only receive messages sent from hosted web pages if this key is declared. The "externally_connectable" declaration will block messages from other extensions, unless the allowed extension ID is declared in the "ids" list.
3Internet-hosted web pages that use runtime.sendMessage to communicate with extensions MUST be explicitly specify the hosting site's domain in the manifest under the "externally_connectable" key.
4 Use of the browser.i18n object does not require a manifest permission declaration. However, the manifest does require a value (default_locale) that is necessary and cannot be specified by the extension author in script code.

Expressing Availability in WebIDL

This specification uses WebIDL [[WEBIDL]] to describe the Browser Extensions API.

Attribute: Exposed

To express the aforementioned conditional situations in which certain APIs are made available due to context, the following contexts are used:

  • Window - The primary context for most browser extension APIs. This applies to background, event, popup, options and custom contexts
  • ContentScript - Applies to content script context

Extended Attribute: CheckAnyPermissions

To express the aforementioned conditional situations in which certain APIs are made available due to expressed manifest keys or permissions, the new WebIDL extended attribute "CheckAnyPermissions" is used.

API objectCheckAnyPermissions ValueManifest Key or Value
browser"browserExt"N/A
browser.browserAction"browserExtBrowserAction""browserAction":[...]
browser.contextMenu"browserExtContextMenus""permissions":["contextMenus"]
browser.extension"browserExt"

i18n"browserExt""default_language": "<code>"
pageAction"browserExtPageAction""pageAction":[...]
runtime"browserExt"

tabs"browserExtTabs""permissions":["tabs"] or
"permissions":["activeTab"]
webNavigation"browserExtWebNavigation""permissions":["webNavigation"]
webRequest"browserExtWebRequest""permissions":["webRequest"]
windows"browserExt"

Example: browser.i18n

In this example, the i18n API should be made available to both browser host scripts (background, event, popup, options, etc.) and content scripts. Use of this API does not require a manifest permission declaration. Additionally, however, the manifest does require a value (default_locale) that is necessary and cannot be specified by the extension author in script code. This is expressed as a BrowserExtManifest dictionary.

NOTE: To avoid naming conflicts with WebIDL definitions elsewhere in this document, the Example below has an underscore ("_") appended to end of interface names. In the actual definitions elsewhere in this document, the underscore character is not used.

  1. First, declare the methods for the browser.i18n object.
    [NoInterfaceObject]
    interface BrowserExtI18n_ {
        DOMString getMessage_(DOMString messageName, sequence<DOMString?> substitutions);
    };
    
  2. Next, we specify the available contexts ("Window" for background/event/popup/options...) and "ContentScript" for the content context.
    [NoInterfaceObject, Exposed=(Window,ContentScript)] 
    interface BrowserExtI18nAPI_ {
        readonly attribute BrowserExtI18n_ i18n;
    };
                            
  3. Connect the i18n object to the browser.* object.
    Browser implements BrowserExtI18nAPI_;
    
  4. Finally, we express the locale from manifest.json. For example "default_locale": "en"
    partial dictionary BrowserExtManifest_ {
        DOMString? defaultLocaleValue;
    };
    

ConsiderationsContent Security Policy (CSP) Restrictions

Use of some JavaScript APIs such as eval() are restricted due to CSP. If an explicit policy is not specified, the default policy is applied. The default CSP is discussed in the specification [[CSP3]] . If the browser extension author specifies a new CSP, it will override the default CSP. Refer to the CSP Overview section for more information about the availability of these APIs. The Cross-domain Privileges and Content and Background Script Communication sections provide details about API usage by content scripts.

  • Script execution via eval() and inline script execution are not allowed
  • Only script from the extension's package can be executed
  • Executing script from the web is not allowed

The browser object

Overview

The core Browser Extension API objects are accessible from the browser object. Their availability varies, depending on conditions outlined in the API Availability section.

  • browserAction
  • contextMenus
  • extension
  • i18n
  • pageAction
  • runtime
  • tabs
  • webNavigation
  • webRequest
  • windows

Context

This API is available in Window context (background, event, popup, options and custom pages), Content Script context, and Internet-hosted web page context.

WebIDL Definition

A description of the special WebIDL syntax considerations for browser extensions are defined elsewhere in this document.

[CheckAnyPermissions_browserExt_]
interface BrowserExtGlobal {
    readonly attribute Browser browser;
};
Window implements BrowserExtGlobal;

[NoInterfaceObject] 
interface Browser { 
};
dictionary BrowserExtIcon {
    DOMString path;
    DOMString size;
};
typedef sequence<BrowserExtIcon> BrowserExtIconArray;
dictionary BrowserExtDeveloper {
    DOMString name;
    DOMString? url;
};
dictionary BrowserExtBrowserOrPageAction {
    BrowserExtIcon? defaultIcon; 
    DOMString? defaultPopup;
    DOMString? defaultTitle;
};
dictionary BrowserExtKeyValue {
    DOMString key;
    DOMString? value;
};
dictionary BrowserExtBrowserSpecificSettings {
    DOMString browserName;
    sequence<BrowserExtKeyValue> keyValue;
};
dictionary BrowserExtBackroundOrEvent {
    DOMString? page;
    boolean persistent;
    sequence<DOMString>? scripts;
};
dictionary BrowserExtContentScripts {
    boolean allFrames;
    sequence<DOMString>? css;
    sequence<DOMString>? excludeMatches;
    sequence<DOMString>? js;
    sequence<DOMString> matches;
    DOMString? runAt;
};
dictionary BrowserExtManifest {
    BrowserExtBackroundOrEvent? background;
    BrowserExtBrowserOrPageAction? browserAction;
    BrowserExtBrowserSpecificSettings? browserSpecificSettings;
    BrowserExtContentScripts? contentScripts;
    DOMString? contentSecurityPolicy;
    DOMString? defaultLocale;
    DOMString? description;
    BrowserExtDeveloper? developer;
    BrowserExtIconArray? icons;
    DOMString? manifestVersion;
    DOMString name;
    DOMString? optionsPage;
    BrowserExtBrowserOrPageAction? pageAction;
    sequence<DOMString>? permissions;
    sequence<DOMString>? requiredKeys;
    DOMString? version;
    sequence<DOMString> webAccessibleResources;
};

Definitions

BrowserExtGlobal
The interface for the main browser object that provides access to all if the child core objects (e.g. browser.browserAction, browser.contextMenus, etc.) and their associated APIs.
browser
The core object that provides all of the browser extension APIs.
Browser
The interface definition is empty in this section, but each subsequent spec section for the core objects (e.g. BrowserAction, ContextMenus, etc.) includes declarations (e.g. Browser implements BrowserExtBrowserActionAPI) that add the corresponding core objects to the browser> object.
BrowserExtIcon
Represents information about a graphical image for BrowserAction or PageAction buttons displayed in the browser UI.
path
Specifies the relative location of the .jpg file.
size
Specifies the width and height of the image in pixels.
BrowserExtIconArray
An array of BrowserExtIcon objects.
BrowserExtDeveloper
Specifies information about the creator of the extension.
name
Specifies the name or company that created the extension.
url
Specifies the company or product URL for the extension.
BrowserExtBrowserOrPageAction
Represents information about either a BrowserAction or PageAction.
defaultIcon
The BrowserExtIcon image, if one was specified in the manifest.json file, or null if none is provided.
defaultPopup
The relative path to the page or script to be invoked if one was specified in the manifest.json file, or null if none is provided.
defaultTitle
The button (or tooltip) text if specified in the manifest.json file, or null if none is provided.
BrowserExtKeyValue
A pair of strings, one representing a lookup "key" (or index) and the other an associated "value".
key
A string lookup "key" (e.g. "color"), which provides access to an associated "value" (e.g. "red").
value
Using an associated lookup "key" (e.g. "color"), this represents the "value" (e.g. "red") for that key.
BrowserExtBrowserSpecificSettings
Used for settings specific to a host such as Gecko, Opera, or Edge.
browserName
The browser name that is associated with the settings, such as "geko" or "opera" or "edge".
keyValue
The pair of name and value for a setting that is only applicable to a particular browser.
BrowserExtBackroundOrEvent
Represents manifest.json settings for long-running or inter-tab scripts.
page
Specifies the relative path to the page that is loaded as the Background or Event page.
persistent
Specifies whether the page is always loaded (true) or is unloaded when not needed (false), such as an idle state.
scripts
Specifies the relative path to the script that is loaded as the Background or Event page.
BrowserExtContentScripts
Represents the collection of information needed to associate script files to be executed when the user navigates the browser to particular URLs.
allFrames
Specifies whether the script should be run for child frames of a page as well as the main page.
css
Specifies relative paths to style sheets to be loaded when the matches/exclude_matches and run_at criteria are met.
excludeMatches
Specifies URL patterns for which the content script will not be run.
js
Specifies relative paths to scripts to be run when the matches/exclude_matches and run_at criteria are met.
matches
Specifies URL patterns for which the content script will not be run.
runAt
Specifies when scripts and CSS will be applied (e.g. "document_start" or "document_end").
BrowserExtManifest
Represents all of the relevant data provided in the manifest.json file.
background
Corresponds to the "background": {} key and associated children in the manifest.json file.
browserAction
Corresponds to the "browser_action": {} key and associated children in the manifest.json file.
browserSpecificSettings
Corresponds to the "browser_specific_settings": {} key and associated children in the manifest.json file.
contentScripts
Corresponds to the "content_scripts": {} key and associated children in the manifest.json file.
contentSecurityPolicy
Corresponds to the "content_security_policy" key/value pair in the manifest.json file.
defaultLocale
Corresponds to the "default_locale" key/value pair in the manifest.json file.
description
Corresponds to the "description" key/value pair in the manifest.json file.
developer
Corresponds to the "developer": {} key and associated children in the manifest.json file.
icons
Corresponds to the "icons": {} key and associated children in the manifest.json file.
manifestVersion
Corresponds to the "manifest_version" key/value pair in the manifest.json file.
name
Corresponds to the "name" key/value pair in the manifest.json file.
optionsPage
Corresponds to the "options_page" key/value pair in the manifest.json file.
pageAction
Corresponds to the "page_action": {} key and associated children in the manifest.json file.
permissions
Corresponds to the "permissions": {} key and associated children in the manifest.json file.
requiredKeys
Corresponds to the "required_keys": [] key and associated children in the manifest.json file.
version
Corresponds to the "version" key/value pair in the manifest.json file.
webAccessibleResources
Corresponds to the "web_accesible_resources": {} key/value pair in the manifest.json file.

The browserAction object

Overview

The browserAction object adds an always-visible button to the browser application, usually near the top of the browser application UI in the toolbar area. An extension that declares a browserAction cannot have a pageAction, and vice-versa.

Manifest

The "browser_action" and "default_title" keys are required. The other keys are optional.
"browser_action": {                               // Required
    "default_icon": {...},                        // Same format as "icons"
    "default_popup": "Page URL",                  // Optional
    "default_title": "Title string"               // Required
}

Context

This API is available in Window context (background, event, popup, options and custom pages).

WebIDL Definition

A description of the special WebIDL syntax considerations for browser extensions are defined elsewhere in this document.

dictionary BrowserExtBrowserActionDefaults {
    BrowserExtIconArray? defaultIcon;
    DOMString? defaultPopup;
    DOMString?  defaultTitle;
};
partial dictionary BrowserExtManifest {
        BrowserExtBrowserActionDefaults? browserActionDefaults;
};
typedef sequence<byte> BrowserExtColorArray;
dictionary BrowserExtTabIdDetails {
    long tabId;
};
dictionary BrowserExtBadgeColorArrayTabId {
    BrowserExtColorArray color;
    long tabId;
};
dictionary BrowserExtBadgePathTabId {
    DOMString path;
    long tabId;
};
dictionary BrowserExtBadgeTextTabId {
    long tabId;
    DOMString text;
};
dictionary BrowserExtBadgeTabIdPopup {
    DOMString popupHTMLFileName;
    long tabId;
};
callback BrowserExtBrowserActionOnClickedCallback = void (BrowserExtTabsTab tab);
[NoInterfaceObject]
interface BrowserExtBrowserAction {
    void disable(long tabId);
    void enable(long tabId);
    Promise<BrowserExtColorArray> getBadgeBackgroundColor(BrowserExtTabIdDetails details);
    Promise<DOMString?> getBadgeText(BrowserExtTabIdDetails details);
    Promise<DOMString?> getPopup(BrowserExtTabIdDetails details);
    BrowserExtEvent onClicked(BrowserExtBrowserActionOnClickedCallback callback);
    void setBadgeBackgroundColor(BrowserExtBadgeColorArrayTabId details);
    void setBadgeText(BrowserExtBadgeTextTabId details);
    Promise<void> setIcon(BrowserExtBadgePathTabId details);
    void setPopup(BrowserExtBadgeTabIdPopup details);
};
[NoInterfaceObject, Exposed=Window, CheckAnyPermissions_browserExtBrowserAction_]
interface BrowserExtBrowserActionAPI {
    readonly attribute BrowserExtBrowserAction browserAction; 
};
Browser implements BrowserExtBrowserActionAPI;

Definitions

BrowserExtBrowserActionDefaults
Represents the initial state of the BrowserAction button, as specified by values in the manifest.json file.
defaultIcon
The initial image to be displayed for the BrowserAction button in the browser UI, as specified by values in the manifest.json file.
defaultPopup
The relative path to the page to be displayed when the BrowserAction button is clicked, as specified by values in the manifest.json file.
defaultTitle
The initial text string to be displayed with the BrowserAction button in the browser UI, as specified by values in the manifest.json file.
browserActionDefaults
Object that represents the initial state of the BrowserAction button, as specified by values in the manifest.json file.
BrowserExtColorArray
RGBA for the BrowserAction button's color.
BrowserExtTabIdDetails
An object that is passed as a parameter to many browser.browserAction methods. The object encapsulates the information needed to execute the associated method.
tabId
The numeric integer ID representing the tab of interest.
BrowserExtBadgeColorArrayTabId
An object that is returned as a Promise from calls to the browser.getBadgeBackgroundColor methods.
color
The RGBA color of the BrowserAction button's background.
tabId
The numeric integer ID for the associated tab.
BrowserExtBadgePathTabId
An object that is passed as a parameter to the browserAction.setIcon() method.
path
The relative path to the image to be displayed in the BrowserAction button in the UI.
tabId
The numeric integer ID for the associated tab.
BrowserExtBadgeTextTabId
An object that is passed as a parameter to the browserAction.setBadgeText() method.
tabId
The numeric integer ID for the associated tab.
text
The text string to be displayed in the BrowserAction button in the UI.
BrowserExtBadgeTabIdPopup
An object that is passed as a parameter to the browserAction.setPopup() method.
popupHTMLFileName
The relative path to the page to be displayed when the BrowserAction button in the UI is activated.
tabId
The numeric integer ID for the associated tab.
BrowserExtBrowserActionOnClickedCallback
This callback handles the browserAction.onClicked() event.
BrowserExtBrowserAction
The definition for the browser.browserAction object.
disable
Indicates that the browser should alter the BrowserAction button in the browser UI so that it cannot be activated, typically visually changing the UI as well to indicate this state to users.
enable
Indicates that the browser should alter the BrowserAction button in the browser UI so that it can be activated, typically visually changing the UI as well to indicate this state to users.
getBadgeBackgroundColor
Returns the color of background for the BrowserAction button in the UI.
getBadgeText
Returns the UI string for the BrowserAction button badge text.
getPopup
Returns the relative path to the page to be displayed when the user actives the BrowserAction in the browser UI.
onClicked
The event that fires when the user activates the BrowserAction button.
setBadgeBackgroundColor
Specifies a new color to be displayed in the as the background for the BrowserAction button in the browser UI.
setBadgeText
Specifies a new text string to be displayed in the BrowserAction button in the browser UI.
setIcon
Specifies a new image to be displayed in the BrowserAction button in the browser UI.
setPopup
Specifies the relative path to the page to be displayed when the user actives the BrowserAction in the browser UI.
BrowserExtBrowserActionAPI
The interface for the browser.browserAction object.
browserAction
The browser.browserAction object.

The contextMenus object

Overview

The contextMenus object allows additional entries to be added to the browser's context menu. The menu will be selectively be shown for various browser UI elements (browser action or page action button) or page elements (frame, image, link, page, selection, etc.).

Manifest

A "contextMenus" entry MUST be declared in the "permissions" key. The icon keys are optional.

"permissions": [                                  // Required
    "contextMenus"                                // Required
],                                                // Required
"icons": {                                        // Optional
    "<size>":"<name.png>"                         // Optional, size 16 recommended
}                                                 // Optional

Context

This API is available in Window context (background, event, popup, options and custom pages).

WebIDL Definition

A description of the special WebIDL syntax considerations for browser extensions are defined elsewhere in this document.

enum BrowserExtContextType { "all", "audio", "browser_action", "editable", "frame", "image", "link", "page", "page_action", "selection", "video" };
enum BrowserExtItemType { "checkbox","normal","radio","separator" };
dictionary BrowserExtContextMenuCreateDetails {
    boolean checked;
    sequence<ContextType>? contexts;
    sequence<DOMString>? documentUrlPatterns;
    boolean enabled;
    DOMString? id;
    Function onclick;
    (long or DOMString?) parentId;
    sequence<DOMString>? targetUrlPatterns;
    DOMString? title;
    DOMString? type;
};
dictionary BrowserExtContextMenuUpdateDetails {
    boolean checked;
    sequence<BrowserExtContextType>? contexts;
    sequence<DOMString>? documentUrlPatterns;
    boolean enabled;
    Function onclick;
    long parentId;
    sequence<DOMString>? targetUrlPatterns;
    DOMString? title;
    ItemType? type;
};
dictionary BrowserExtContextMenuOnClickedDetails {
    boolean checked;
    boolean editable;
    long frameId;
    DOMString? frameUrl;
    DOMString? linkUrl;
    DOMString? mediaType;
    (long or DOMString) menuItemId;
    DOMString? pageUrl;
    (long or DOMString?) parentMenuItemId;             
    DOMString? selectionText;
    DOMString? srcUrl;
    boolean wasChecked;
};
callback BrowserExtContextMenuOnClickedCallback = void (BrowserExtContextMenuOnClickedDetails details, BrowserExtTabsTab tab);
[NoInterfaceObject]
interface BrowserExtContextMenus {
    Promise<long> create(BrowserExtContextMenuCreateDetails details);
    BrowserExtEvent onClicked(BrowserExtContextMenuOnClickedCallback callback);
	Promise<void> remove((long or DOMString) itemId);
    Promise<void>  removeAll();
    Promise<void>  update((long or DOMString) itemId, BrowserExtContextMenuUpdateDetails details);
};
[NoInterfaceObject, Exposed=Window, CheckAnyPermissions_browserExtContextMenus_]
interface BrowserExtContextMenusAPI {
    readonly attribute BrowserExtContextMenus contextMenus; 
};
Browser implements BrowserExtContextMenusAPI;

Definitions

BrowserExtContextType
Specifies whether a context menu item is displayed for certain conditions.
all
Applies in any of the contexts.
audio
Applies when the user context-clicks an audio element.
browser_action
Applies when the user context-clicks the BrowserAction button in the browser UI.
editable
Applies when the user context-clicks an editable element in the active tab, like a textarea.
frame
Applies when the user context-clicks in a nested iframe in the active tab.
image
Applies when the user context-clicks an image in the active tab.
link
Applies when the user context-clicks on a link in the active tab.
page
Applies when the user context-clicks in the page in the active tab, but none of the other page contexts apply (for example, the click is not on an image or a nested iframe or a link).
page_action
Applies when the user context-clicks the PageAction button in the browser UI.
selection
Applies when part of the page in the active tab is selected.
video
Applies when the user context-clicks a video element in the active tab.
BrowserExtItemType
Defines the UI control type to be associated with menu item text.
checkbox
A context menu item that represents a binary state. It displays a checkmark next to the label. Clicking the item toggles the checkmark. The contextMenus.onClicked listener will be passed two extra properties: "checked", indicating whether the item is checked now, and "wasChecked", indicating whether the item was checked before the click event.
normal
A context menu item that just displays a label.
radio
A context menu item that represents one of a group of choices. Just like a checkbox, this also displays a checkmark next to the label, and its contextMenus.onClicked listener is passed "checked" and "wasChecked". However, if you create more than one radio item, then the items function as a group of radio items: only one item in the group can be checked, and clicking an item makes it the checked item.
separator
A line separating a group of items.
BrowserExtContextMenuCreateDetails
Details for the new context menu item.
checked
boolean. The initial state of a checkbox or radio item: true for selected and false for unselected. Only one radio item can be selected at a time in a given group of radio items.
contexts
array of contextMenus.ContextType. Array of contexts in which this menu item will appear. Defaults to ['page'] if not specified.
documentUrlPatterns
array of string. Similar to documentUrlPatterns, but lets you filter based on the src attribute of img/audio/video tags and the href of anchor tags.
enabled
boolean. Whether this context menu item is enabled or disabled. Defaults to true.
id
string. The unique ID to assign to this item. Mandatory for event pages. Cannot be the same as another ID for this extension.
onclick
function. A function that will be called when the menu item is clicked. Event pages cannot use this: instead, they should register a listener for contextMenus.onClicked.
parentId
integer or string. The ID of a parent menu item; this makes the item a child of a previously added item.
targetUrlPatterns
array of string. Similar to documentUrlPatterns, but lets you filter based on the src attribute of img/audio/video tags and the href of anchor tags.
title
istring. The text to be displayed in the item. Mandatory unless type is "separator". You can use "%s" in the string. If you do this, and some text is selected in the page when the context menu is shown, then the selected text will be interpolated into the title. For example, if title is "Translate '%s' to Pig Latin" and the user selects the word "cool", then activates the context menu, then the context menu item's title will be: "Translate 'cool' to Pig Latin".
type
contextMenus.ItemType. The type of menu item: "normal", "checkbox", "radio", "separator". Defaults to "normal".
BrowserExtContextMenuUpdateDetails
The details to update. Accepts the same values as create().
checked
boolean. The initial state of a checkbox or radio item: true for selected and false for unselected. Only one radio item can be selected at a time in a given group of radio items.
contexts
array of contextMenus.ContextType. Array of contexts in which this menu item will appear. Defaults to ['page'] if not specified.
documentUrlPatterns
array of string. Lets you restrict the item to apply only to documents whose URL matches one of the given match patterns. This applies to frames as well.
enabled
boolean. Whether this context menu item is enabled or disabled. Defaults to true.
onclick
function. A function that will be called when the menu item is clicked. Event pages cannot use this: instead, they should register a listener for contextMenus.onClicked.
parentId
integer or string.  The ID of a parent menu item; this makes the item a child of a previously added item. Note: You cannot change an item to be a child of one of its own descendants.
targetUrlPatterns
array of string. Similar to documentUrlPatterns, but lets you filter based on the src attribute of img/audio/video tags and the href of anchor tags.
title
string. The text to be displayed in the item; this is mandatory unless type is "separator".
type
contextMenus.ItemType. The type of menu item: "normal", "checkbox", "radio", "separator". Defaults to "normal".
BrowserExtContextMenuOnClickedDetails
Information sent when a context menu item is clicked.
checked
boolean. A flag indicating whether a checkbox or radio item was checked after it was clicked.
editable
boolean. A flag indicating whether the element is editable: for example, if it is a textarea.
frameId
integer or string. The ID of the frame that was clicked.
frameUrl
string. The URL of the frame of the element where the context menu was clicked, if it was in a frame.
linkUrl
string. If the element is a link, the URL it points to.
mediaType
string. One of "image", "video", or "audio" if the context menu was activated on one of these types of elements.
menuItemId
integer or string. The ID of the menu item that was clicked.
pageUrl
string. The URL of the page in which the menu item was clicked. This property is not present if the click occured in a context where there is no current page, such as on a browser action.
parentMenuItemId
integer or string. The parent ID, if any, for the item clicked.
selectionText
string. If some text was selected in the page, this contains the selected text./dd>
srcUrl
string. Will be present for elements with a "src" URL.
wasChecked
boolean. A flag indicating whether a checkbox or radio item was checked before it was clicked.
BrowserExtContextMenuOnClickedCallback
The callback for the browser.contextMenus object.
BrowserExtContextMenus
Defines the browser.contextMenus object.
create
Creates a new context menu item, given an options object defining properties for the item. Unlike other asynchronous functions, this one does not return a promise, but uses an optional callback to communicate success or failure. This is because its return value is the ID of the new item.
BrowserExtContextMenus.onClicked
Fired when a context menu item is clicked.
remove
Removes a context menu item. This is an asynchronous function that returns a Promise.
removeAll
Removes all context menu items added by this extension. This is an asynchronous function that returns a Promise.
update
Updates a previously created context menu item. This is an asynchronous function that returns a Promise.
BrowserExtContextMenusAPI
The interface for the browser.contextMenus object.
contextMenus
The browser.contextMenus object.

The i18n object

Overview

The i81n object provides a way to access strings that have been localized into supported languages.

Manifest

When providing localized strings, you MUST specify a default locale using a two-character code. Codes can be found at RFC1766 or IETF BCP47. When localizing manifest strings, the following syntax is used.

"default_locale" : "<twoCharLocaleCode>",              // Required
"name" : "__MSG_<yourCustomNameStringIdentifier>__",
"description" : "__MSG_<yourCustomDescriptionStringIdentifier>__",
For example
"default_locale" : "en",              // English
"name" : "__MSG_MySampleExtension__",
"description" : "__MSG_MySampleExensionDecription__",

Localized Strings

Each supported locale MUST have its own messages.json file stored in the folder _locales/<twoCharLocaleCode>. The two-character codes used for directory names here the same as are used in the mainfest.json to specify default_locale.

Locale Codes and Matching

Locale codes used in file/directory names and returned by the API, contrary to common standards, are in the form:

<language>[_<region>]

Which is to say, a two-letter language code, optionally followed by an underscore and a two-letter region code. Locale codes are matched such that an exact match is used if available, falling back to the least-specific, closest match. Therefore, for "en_US", the following locales would be chosen, in order of preference:

  • en_US
  • en_US_var
  • en
  • en_GB
  • en_GB_var

String tokens

Strings are localized by pre-processing messages, replacing |$[a-zA-Z0-9@_]+$| tokens with the value of their replacements. Later, it processes the resulting string for |$[0-9]| replacements.

Any number of sequential |$|s are permitted, and are replaced with that number minus 1. Instances of |$| followed by any number of sequential digits is also permitted, but a localized string which provides more than 9 substitutions are ignored.

Locale Message Replacement

Locale messages in the form __MSG_<message name>_ are automatically replaced with the appropriate localized message in CSS files and certain manifest.json string values. Specifically, the replacements are done according to the regular expression __MSG_([A-Za-z0-9@_]+?)__, meaning that the first occurrence of __ terminates the message name immediately.

CSS files are pre-processed as a raw text stream, with no considerations for CSS syntax. manifest.json values are processed after the JSON has been parsed, and the results are always treated as literal strings. The following manifest keys are processed for localization messges:

  • name
  • short_name
  • description
  • author
  • homepage_url
  • developer.name
  • developer.url
  • browser_action.default_title
  • browser_action.default_url
  • page_action.default_title
  • page_action.default_url

Placeholders

It is possible for a translated string to contain substrings that will not be translated or will be replaced with variable content. For example

"messageExample": {
    "message": "You clicked $URL$.",
    "description": "Tells the user which link they clicked.",
    "placeholders": {
      "url" : {
        "content" : "$1"
        "example" : "https://www.w3.org"
      }

The placeholder name ("url" in the above example) is used to represent the placeholder in the substitution string (e.g. "url" becomes $URL$). It is case insensitive and can contain the same characters as a message string name.

The "content" item defines the content of the placeholder. This can be a hardcoded string, such as "My placeholder", but it can also include values obtained from a i18n.getMessage() call.

The optional "example" item is intended to help translators by showing them an example of how the placeholder would appear to end users, allowing them to make the best choice when localizing the file.

Context

This API is available in Window context (background, event, popup, options and custom pages) and Content Script context.

WebIDL Definition

A description of the special WebIDL syntax considerations for browser extensions are defined elsewhere in this document.

    
[NoInterfaceObject]
interface BrowserExtI18n {
    DOMString getMessage(DOMString messageName, sequence<DOMString?>? substitutions);
};
[NoInterfaceObject, Exposed=(Window,ContentScript), CheckAnyPermissions_browserExt_] 
interface BrowserExtI18nAPI {
        readonly attribute BrowserExtI18n i18n;
};
Browser implements BrowserExtI18nAPI;
partial dictionary BrowserExtManifest {
    DOMString? defaultLocaleValue;
};

Definitions

BrowserExtI18n
Interface for retrieving strings that have been translated into the appropriate language and format for a corresponding locale.
getMessage
Gets the localized string for the specified message.
BrowserExtI18nAPI
The interface for the browser.i18n object.
i18n
The browser.i18n object.
defaultLocaleValue
This key must be present in manifest.jsonif the extension contains the _locales directory, and must be absent otherwise. It identifies a subdirectory of _locales, and this subdirectory will be used to find the default strings for your extension.

The pageAction object

Overview

The pageAction object adds a button to the browser application, usually within the address bar. This button typically appears only when the extension has detected that it can perform an action on the current page for the active tab. An extension that declares a browserAction cannot have a pageAction, and vice-versa.

Manifest

The "page_action" and "default_title" keys are required. The other keys are optional.

"page_action": {                               // Required
    "default_icon": {...},                        // Same format as "icons"
    "default_popup": "Page URL",                  // Optional
    "default_title": "Title string"               // Required
}

Context

This API is available in Window context (background, event, popup, options and custom pages).

WebIDL Definition

A description of the special WebIDL syntax considerations for browser extensions are defined elsewhere in this document.

dictionary BrowserExtPageActionDefaults {
    BrowserExtIconArray? defaultIcon;
    DOMString? defaultPopup;
    DOMString?  defaultTitle;
};
partial dictionary BrowserExtManifest {
    BrowserExtPageActionDefaults? pageActionDefaults;
};
dictionary BrowserExtBadgePath {
    DOMString path;
};
callback BrowserExtPageActionOnClickedCallback = void (BrowserExtTabsTab tab);
interface BrowserExtPageAction {
    Promise<DOMString?> getPopup(BrowserExtTabIdDetails details);
    Promise<DOMString?> getTitle(BrowserExtTabIdDetails details);
    void hide(long tabId);
    BrowserExtEvent onClicked(BrowserExtPageActionOnClickedCallback callback);
    Promise<void> setIcon(BrowserExtBadgePath path);
    void setPopup(BrowserExtBadgePathTabId details);
    void setTitle(BrowserExtBadgeTextTabId details);
    void show(long tabId);
};
[NoInterfaceObject, Exposed=Window, CheckAnyPermissions_browserExtPageAction_]
interface BrowserExtPageActionAPI {
    readonly attribute BrowserExtPageAction pageAction; 
};
Browser implements BrowserExtPageActionAPI;

Definitions

BrowserExtPageActionDefaults
Represents the initial state of the PageAction button, as specified by values in the manifest.json file
defaultIcon
The initial image to be displayed for the PageAction button in the browser UI, as specified by values in the manifest.json file.
defaultPopup
The relative path to the page to be displayed when the PageAction button is clicked, as specified by values in the manifest.json file.
defaultTitle
The initial text string to be displayed with the BrowserAction button in the browser UI, as specified by values in the manifest.json file.
pageActionDefaults
Object that represents the initial state of the PageAction button, as specified by values in the manifest.json file.
BrowserExtBadgePath
An object that is passed as a parameter to the pageAction.setIcon() method.
path
The relative path to the image to be displayed in the PageAction button in the UI.
BrowserExtPageActionOnClickedCallback
This callback handles the pageAction.onClicked() event.
BrowserExtPageAction
The definition for the browser.pageAction object.
getPopup
Returns the relative path to the page to be displayed when the user actives the PageAction in the browser UI.
getTitle
Returns the UI string for the PageAction button title text.
hide
Hides the page action for a given tab.
onClicked
The event that fires when the user activates the PageAction button.
setIcon
Specifies a new image to be displayed in the PageAction button in the browser UI.
setPopup
Specifies the relative path to the page to be displayed when the user actives the PageAction in the browser UI.
setTitle
Specifies a new text string to be displayed for the PageAction button in the browser UI.
show
integer. The ID of the tab for which you want to show the page action.
BrowserExtPageActionAPI
The interface for the browser.pageAction object.
pageAction
The browser.pageAction object.

The runtime object

Overview

The runtime object is used to send and receive messages across contexts, as well as access extension-level information such as the id, manifest, and absolute path to resources.

Manifest

There are no additional manifest entries required for an extension to use this object. However, an extension will only receive messages sent from hosted web pages if the “externally_connectable” key is declared. Also, an extension will block messages from other extensions by specifying only approved extensions. Note that if this key is used to allow web pages to send messages, unless "ids" : ["*"] is specified, all messages from other extensions will be blocked. URLs in the "matches" array MUST include a top-level domain. This list does not affect content scripts.

"externally_connectable" : [
    "ids":[...], // Identifiers for other extensions that are allowed to send messages
    "matches":[...] // URL patterns for hosted web pages allowed to send messages 
    ]

Context

This API is available in Window context (background, event, popup, options and custom pages), Content Script context, and Internet-hosted web page context.

WebIDL Definition

A description of the special WebIDL syntax considerations for browser extensions are defined elsewhere in this document.

enum BrowserExtRuntimeOnInstalledReason {"browser_update", "extension_install", "extension_update"};
dictionary BrowserExtRuntimeOnInstalledDetails {
    BrowserExtRuntimeOnInstalledReason reason;
    DOMString? previousVersion;
    DOMString? id;
};
dictionary BrowserExtRuntimePort {
    Function disconnect;
    DOMString name;
    object onDisconnect;
    object onMessage;
    Function postMessage;
    BrowserExtRuntimeMessageSender? sender;
};
dictionary BrowserExtRuntimeMessageSender {
    DOMString? id;
    long frameId;
    BrowserExtTabsTab? tab;
    DOMString? url;
};
callback BrowserExtRuntimeOnConnectCallback = void (BrowserExtRuntimePort port);
callback BrowserExtRuntimeOnInstalledCallback = void (BrowserExtRuntimeOnInstalledDetails details);
callback BrowserExtRuntimeOnMessageCallback = void (optional any message, BrowserExtRuntimeMessageSender sender, BrowserExtRuntimeSendResponseCallback callback);
[NoInterfaceObject]
interface BrowserExtBrowserRuntime {
    object getManifest();
    DOMString getURL(DOMString path);
    attribute DOMString id;
    void onConnect(BrowserExtRuntimeOnConnectCallback callback);
    void onInstalled(BrowserExtRuntimeOnInstalledCallback callback);
    void onMessage(BrowserExtRuntimeOnMessageCallback callback);
    Promise<any> sendMessage(optional DOMString extensionId, any message);
    attribute BrowserExtRuntimePort Port;
    attribute BrowserExtRuntimeMessageSender MessageSender;
};
[NoInterfaceObject, Exposed=Window, CheckAnyPermissions_browserExt_]
interface BrowserExtRuntimeAPI {
    readonly attribute BrowserExtRuntime runtime; 
};
Browser implements BrowserExtRuntimeAPI;

Definitions

BrowserExtRuntimeOnInstalledReason
The reason that the runtime.onInstalled event is being dispatched.
browser_update
The browser was updated to a new version.
extension_install
The extension was installed.
extension_update
The extension was updated to a new version.
BrowserExtRuntimeOnInstalledDetails
Details provided when the runtime.onInstalled event is fired.
reason
A runtime.OnInstalledReason value stating the reason that this event is being dispatched.
previousVersion
string. Indicates the previous version of the extension that was just updated. This is present only if the reason value is update.
id
string. Indicates the ID of the module that updated.
BrowserExtRuntimePort
Represents one end of a connection between two specific contexts, which can be used to exchange messages.
disconnect
function. Disconnects a port. Either end can call this when they have finished with the port. It will cause onDisconnect to be fired at the other end. This is useful if the other end is maintaining some state relating to this port, which can be cleaned up on disconnect. If this port is connected to a native application, this function will close the native application.
name
string. The port's name, defined in the runtime.connect() or tabs.connect() call that created it. If this port is connected to a native application, its name is the name of the native application.
onDisconnect
object. This contains the addListener() and removeListener() functions common to all events in browser extensions. Listener functions will be called when the other end has called Port.disconnect(). This event will only be fired once for each port. The listener function will be passed the Port object. If the port was disconnected due to an error, then the Port argument will contain an error property giving more information about the error.
onMessage
object. This contains the addListener() and removeListener() functions common to all events in browser extensions. Listener functions will be called when the other end has sent this port a message. The listener will be passed the JSON object that the other end sent.
postMessage
function. Send a message to the other end. This takes one argument, which is a JSON object representing the message to send. It will be delivered to any script listening to the port's onMessage event, or to the native application if this port is connected to a native application.
sender
Contains information about the sender of the message. This property will only be present on ports passed to onConnect or onConnectExternal listeners.
BrowserExtRuntimeMessageSender
An object containing information about the sender of a message or connection request.
id
string. The ID of the extension that sent the message, if the message was sent by an extension. Note that this is the extension's internal ID, not the ID in the manifest.json applications key.
frameId
integer. The frame that opened the connection. Zero for top-level frames, positive for child frames. This will only be set when tab is set.
tab
The tabs.Tab which opened the connection. This property will only be present when the connection was opened from a tab (including content scripts).
url
string. The URL of the page or frame hosting the script that sent the message.
BrowserExtRuntimeOnConnectCallback
The callback fired when a connection is made with either an extension process or a content script.
BrowserExtRuntimeOnInstalledCallback
The callback fired when the extension is first installed, when the extension is updated to a new version, and when the browser is updated to a new version.
BrowserExtRuntimeOnMessageCallback
The callback used to listen for messages from another part of your browser extension.
BrowserExtBrowserRuntime
The definition for the browser.runtime object.
getManifest
Get the complete manifest.json file, serialized to a JSON object.
getURL
Given a relative path from the manifest.json to a resource packaged with the browser extension, return a fully-qualified URL.
id
The ID for this browser extension.
onConnect
Fired when a connection is made with either a browser extension process or a content script.
onInstalled
Fired when the extension is first installed, when the extension is updated to a new version, and when the browser is updated to a new version./dd>
onMessage
Use this event to listen for messages from another part of your browser extension.
sendMessage
Sends a single message to event listeners within your extension or a different extension.
Port
Represents one end of a connection between two specific contexts, which can be used to exchange messages.
MessageSender
An object containing information about the sender of a message or connection request.
BrowserExtRuntimeAPI
The interface for the browser.runtime object.
runtime
The browser.runtime object.

The tabs object

Overview

The tabs object is used to access metadata about a tab, such as its title, or to access the current content within the tab itself.

Manifest

The "tabs" permission is required to use this object. Refer to the activeTab permission section for more information about accessing these APIs.

{
    "permissions": [                               // Required
        "tabs"                                     // Either "tabs" or "activeTab" is required
        "activeTab"                                // Either "tabs" or "activeTab" is required
    ]                                              // Required   
}

Context

This API is available in Window context (background, event, popup, options and custom pages).

WebIDL Definition

A description of the special WebIDL syntax considerations for browser extensions are defined elsewhere in this document.

enum BrowserExtTabMutedReasonDetails { "user", "capture", "extension" };
enum BrowserExtRunAt { "document_end", "document_idle", "document_start" };
enum BrowserExtTabStatus { "complete", "loading" };
enum BrowserExtWindowTypes { "app", "normal", "panel", "popup" };
enum BrowserExtTabsCaptureVisibleTabFormat { "jpeg", "png" };
dictionary BrowserExtTabsTab {
    boolean active;
    boolean audible;
    DOMString? favIconUrl;
    boolean highlighted;
    long height;
    long id;
    boolean incognito;
    long index;
    TabMutedDetails? mutedDetails;
    long openerTabId;
    boolean pinned;
    DOMString? sessionId;
    DOMString? status;
    DOMString? title;
    DOMString? url;
    long width;
    long windowId;
};
dictionary BrowserExtTabMutedDetails {
    DOMString? extensionId;
    boolean muted;
    TabMutedReasonDetails? reason;
};
dictionary BrowserExtTabConnectDetails {
    long frameId;
    DOMString? name;
};
dictionary BrowserExtTabCreateDetails {
    boolean active;
    long index;
    long openerTabId;
    boolean pinned;
    DOMString? url;
    long windowId;
};
dictionary BrowserExtTabScriptAndCSSDetails {
    boolean allFrames;
    DOMString? code;
    DOMString? file;
    long frameId;
    boolean matchAboutBlank;
    BrowserExtRunAt? runAt;
};
dictionary BrowserExtTabsCaptureVisibleTabDetails {
    BrowserExtTabsCaptureVisibleTabFormat imageCaptureFormat;
    long jpegQuality;
};
dictionary BrowserExtTabQueryDetails {
    boolean active;
    boolean audible;  
    boolean currentWindow;
    boolean highlighted;
    long index;
    boolean lastFocusedWindow;
    boolean muted;
    boolean pinned;
    TabStatus? status;
    DOMString? title;
    (DOMString? or sequence<DOMString>?) url;
    long windowId;
    WindowType? windowType;
};
dictionary BrowserExtTabReloadDetails {
    boolean bypassCache;
};
dictionary BrowserExtTabSendMessageDetails {
    long frameId;
};
dictionary BrowserExtTabUpdateDetails {
    boolean active;
    boolean highlighted;
    boolean muted;
    long openerTabId;
    boolean pinned;
    DOMString? url;
};
dictionary BrowserExtTabIdWindowId {
    long tabId;
    long windowId;
};
dictionary BrowserExtTabsWindowIdIsWindowClosing {
    boolean isWindowClosing;
    long windowId;
};
dictionary BrowserExtTabsOnUpdatedChangeDetails {
    boolean audible;    
    DOMString? favIconUrl;
    TabMutedDetails? mutedDetails;
    boolean pinned;
    DOMString? status;
    DOMString? title;
    DOMString? url;
};
callback BrowserExtTabsOnActivatedCallback = void (BrowserExtTabIdWindowId activeDetails);
callback BrowserExtTabsOnCreatedCallback = void (BrowserExtTabTab tab);
callback BrowserExtTabsOnRemovedCallback = void (long tabId, BrowserExtTabsWindowIdIsWindowClosing removeDetails);
callback BrowserExtTabsOnUpdatedCallback = void (long tabId, BrowserExtTabsOnUpdatedChangeDetails details, BrowserExtTabsTab tab);
[NoInterfaceObject]
interface BrowserExtBrowserTabs {
    Promise<DOMString> captureVisibleTab(long windowId, BrowserExtTabsCaptureVisibleTabDetails details);
    RuntimePort connect(long tabId, BrowserExtTabConnectDetails details);
    Promise<BrowserExtTabsTab> create(BrowserExtTabCreateDetails details);
    void executeScript(long tabId, BrowserExtTabScriptAndCSSDetails details);
    Promise<BrowserExtTabsTab> get(long tabId);
    Promise<BrowserExtTabsTab> getCurrent();
    void insertCSS(long tabId, BrowserExtTabScriptAndCSSDetails details);
    void onActivated(BrowserExtTabsOnActivatedCallback callback);
    void onCreated(BrowserExtTabsOnCreatedCallback callback);
    void onRemoved(BrowserExtTabsOnRemovedCallback callback);
    void onUpdated(BrowserExtTabsOnUpdatedCallback callback);
    Promise<BrowserExtTabsTab> query(BrowserExtTabQueryDetails queryDetails);
    Promise<void> reload(BrowserExtTabReloadDetails details);
    Promise<void> remove((long or sequence<long>) tabIds);
    Promise<any> sendMessage(long tabId, any message, optional BrowserExtTabSendMessageOptions details);
    Promise<BrowserExtTabsTab> update(optional long tabId, BrowserExtTabUpdateDetails details);
};
[NoInterfaceObject, Exposed=Window, CheckAnyPermissions_browserExtTabs_]
interface BrowserExtTabsAPI {
readonly attribute BrowserExtTabs tabs; 
};
Browser implements BrowserExtTabsAPI;

Definitions

BrowserExtTabMutedReasonDetails
Specifies the reason a tab was muted or unmuted.
user
The user set the muted state.
capture
Tab capture started, forcing a muted state change.
extension
An extension set the muted state. If this is the reason, extensionId in tabs.mutedInfo will contain the ID of the extension responsible.
BrowserExtRunAt
The soonest that the code will be injected into the tab. Defaults to "document_idle".
document_end
Corresponds to interactive. The DOM has finished loading, but resources such as scripts and images may still be loading.
document_idle
Corresponds to complete. The document and all its resources have finished loading.
document_start
Corresponds to loading. The DOM is still loading.
BrowserExtTabStatus
The status of the tab.
complete
Tab is finished loading.
loading
Tab is not finished loading.
BrowserExtWindowTypes
The type of window that hosts this tab.
app
Application host window.
normal
Normal host window.
panel
Panel host window.
popup
Popup host window.
BrowserExtTabsCaptureVisibleTabFormat
The format of an image.
jpeg
JPEG image format.
png
PNG image format.
BrowserExtTabsTab
Contains information about a tab. This provides access to information about what content is in the tab, how large the content is, what special states or restrictions are in effect, and so forth.
active
boolean. Whether the tab is active in its window. This may be true even if the tab's window is not currently focused.
audible
boolean. If the tab is not muted: whether the tab is producing sound. If the tab is muted: whether the tab would be producing sound, if it were not muted.
favIconUrl
string. The URL of the tab's favicon. Only present if the extension has the "tabs" permission. It may also be an empty string if the tab is loading.
highlighted
boolean. Whether the tab is highlighted.
height
integer. The height of the tab in pixels.
id
integer. The tab's ID. Tab IDs are unique within a browser session. The tab ID may also be set to tabs.TAB_ID_NONE for browser windows that don't host content tabs (for example, devtools windows).
incognito
boolean. Whether the tab is in a private browsing window.
index
integer. The zero-based index of the tab within its window.
mutedDetails
The current muted state for the tab and the reason for the last state change.
openerTabId
integer. The ID of the tab that opened this tab, if any. This property is only present if the opener tab still exists.
pinned
boolean. Whether the tab is pinned.
sessionId
string. The session ID used to uniquely identify a Tab obtained from the sessions API.
status
string. Either loading or complete.
title
string. The title of the tab. Only present if the extension has the "tabs" permission.
url
string. The URL of the document that the tab is displaying. Only present if the extension has the "tabs" permission.
width
integer. The width of the tab in pixels.
windowId
integer. The ID of the window that hosts this tab.
BrowserExtTabMutedDetails
This object contains a boolean indicating whether the tab is muted, and the reason for the last state change.
extensionId
string. The ID of the extension that last changed the muted state. Not set if an extension was not the reason the muted state last changed.
muted
boolean. Whether the tab is currently muted. Equivalent to whether the muted audio indicator is showing.
reason
The reason the tab was muted or unmuted. Not set if the tab's muted state has never been changed.
BrowserExtTabConnectDetails
Information provided to the tabs.connect() method.
frameId
integer. Open a port to a specific frame identified by frameId instead of all frames in the tab
name
string. Will be passed into runtime.onConnect event listeners in content scripts belonging to this extension and running in the specified tab.
BrowserExtTabCreateDetails
Information provided to the tabs.create() method.
active
boolean. Whether the tab should become the active tab in the window. Does not affect whether the window is focused. Defaults to true.
index
integer. The position the tab should take in the window. The provided value will be clamped to between zero and the number of tabs in the window.
openerTabId
integer. The ID of the tab that opened this tab. If specified, the opener tab must be in the same window as the newly created tab.
pinned
boolean. Whether the tab should be pinned. Defaults to false.
url
string. The URL to navigate the tab to initially.
windowId
integer. The window to create the new tab in. Defaults to the current window.
BrowserExtTabScriptAndCSSDetails
Information provided to the tabs.executeScript() and tab.insertCSS() methods.
allFrames
boolean. If true, the code will be injected into all frames of the current page. If true and frameId is set, then the code will be injected into the specified frame and all its child frames. If it is false, code is only injected into the top frame. Defaults to false.
code
string. Code to inject, as a text string.
file
string. Path to a file containing the code to inject. To work cross-browser, specify the path as an absolute URL, starting at the extension's root, like this: "/path/to/script.js".
frameId
integer. The frame where the code should be injected. Defaults to 0 (the top-level frame).
matchAboutBlank
boolean. If true, the code will be injected into blank frames. Defaults to false.
runAt
The soonest that the code will be injected into the tab. Defaults to "document_idle".
BrowserExtTabsCaptureVisibleTabDetails
Information provided to the tabs.captureVisibleTab() method.
imageCaptureFormat
The format of the resulting image. Default is "jpeg".
jpegQuality
integer. When format is "jpeg", this controls the quality of the resulting image. It is a number between 0 and 100. If is is omitted, 92 is used. As quality is decreased, the resulting image will have more visual artifacts, and the number of bytes needed to store it will decrease. This value is ignored for PNG images.
BrowserExtTabQueryDetails
Information provided to the tabs.query() method.
active
boolean. Whether the tabs are active in their windows.
audible
boolean. Whether the tabs are audible.
currentWindow
boolean. Whether the tabs are in the current window.
highlighted
boolean. Whether the tabs are highlighted.
index
integer. The position of the tabs within their windows.
lastFocusedWindow
boolean. Whether the tabs are in the last focused window.
muted
boolean. Whether the tabs are muted.
pinned
boolean. Whether the tabs are pinned.
status
Whether the tabs have completed loading.
title
string. Match page titles against a pattern.
url
string or array of string. Match tabs against one or more match patterns. Note that fragment identifiers are not matched.
windowId
integer. The ID of the parent window, or windows.WINDOW_ID_CURRENT for the current window.
windowType
The type of window the tabs are in.
BrowserExtTabReloadDetails
Information provided to the tabs.reload() method.
bypassCache
boolean. Bypass the local web cache. Default is false.
BrowserExtTabSendMessageDetails
Information provided to the tabs.sendMessage() method.
frameId
integer. Sends the message to a specific frame identified by frameId instead of all frames in the tab.
BrowserExtTabUpdateDetails
Information provided to the tabs.update() method.
active
boolean. Whether the tab should be active. Does not affect whether the window is focused
highlighted
boolean. Adds or removes the tab from the current selection.
muted
boolean. Whether the tab should be muted.
openerTabId
integer. The ID of the tab that opened this tab. If specified, the opener tab must be in the same window as this tab.
pinned
boolean. Whether the tab should be pinned.
url
string. A URL to navigate the tab to. 
BrowserExtTabIdWindowId
Information provided to the tabs.onActivated() callback.
tabId
integer. The ID of the tab that has become active.
windowId
integer. The ID of the tab's window.
BrowserExtTabsWindowIdIsWindowClosing
Information provided to the tabs.onRemoved() callback.
isWindowClosing
boolean. true if the tab is being closed because its window is being closed.
windowId
integer. The window whose tab is closed.
BrowserExtTabsOnUpdatedChangeDetails
Information provided to the tabs.onUpdated() callback.
audible
boolean. The tab's new audible state.
favIconUrl
string. The tab's new favicon URL.
mutedDetails
The tab's new muted state and the reason for the change.
pinned
boolean. The tab's new pinned state.
status
string. The status of the tab. Can be either loading or complete.
title
string. The page's title text string.
url
string. The tab's URL if it has changed.
BrowserExtTabsOnActivatedCallback
Callback for the tabs.onActivated() event.
BrowserExtTabsOnCreatedCallback
Callback for the tabs.onCreated() event.
BrowserExtTabsOnRemovedCallback
Callback for the tabs.onRemoved() event.
BrowserExtTabsOnUpdatedCallback
Callback for the tabs.onUpdated() event.
BrowserExtBrowserTabs
The definition for the browser.tabs object.
captureVisibleTab
Creates a data URI encoding an image of the visible area of the currently active tab in the specified window. You must have the <all_urls> permission to use this method. This is an asynchronous function that returns a Promise.
connect
Call this function to set up a connection between the extension's background scripts (or other privileged scripts, such as popup scripts or options page scripts) and any content scripts that belong to this extension and are running in the specified tab.
create
Creates a new tab. This is an asynchronous function that returns a Promise.
executeScript
Injects JavaScript code into a page. To use this API you must have the permission for the page's URL, either explicitly as a host permission, or using the activeTab permission.
get
Given a tab ID, get the tab's details as a tabs.Tab object. This is an asynchronous function that returns a Promise.
getCurrent
Get a tabs.Tab containing information about the tab that this script is running in. You can call this function in contexts where there is a browser tab, such as an options page. If you call it from a background script or a popup, it will return undefined. This is an asynchronous function that returns a Promise.
insertCSS
Injects CSS into a page. To use this API you must have the permission for the page's URL, either explicitly as a host permission, or using the activeTab permission. You can only inject CSS into pages whose URL can be expressed using a match pattern: meaning, its scheme must be one of "http", "https", "file", "ftp". The inserted CSS may be removed again by calling tabs.removeCSS().This is an asynchronous function that returns a Promise.
onActivated
Fires when the active tab in a window changes. Note that the tab's URL may not be set at the time this event fired, but you can listen to tabs.onUpdated events to be notified when a URL is set.
onCreated
Fired when a tab is created. Note that the tab's URL may not be given its final value at the time this event fired. Browsers may create a new tab with a temporary URL such as "about:blank" before loading the new page into it. You can listen to tabs.onUpdated events to be notified when a URL is set.
onRemoved
Fired when a tab is closed.
onUpdated
Fired when a tab is updated.
query
Gets all tabs that have the specified properties, or all tabs if no properties are specified. This is an asynchronous function that returns a Promise.
reload
Reload a tab, optionally bypassing the local web cache. This is an asynchronous function that returns a Promise.
remove
Closes one or more tabs. This is an asynchronous function that returns a Promise.
sendMessage
Sends a single message from the extension's background scripts (or other privileged scripts, such as popup scripts or options page scripts) and any content scripts that belong to this extension and are running in the specified tab. The message will be received in the content scripts by any listeners to the runtime.onMessage event. Listeners may then optionally send a response back to the background script using the sendResponse argument. This is an asynchronous function that returns a Promise.
update
Navigate the tab to a new URL, or modify other properties of the tab. To use this function, pass the ID of the tab to update, and an updateProperties object containing the properties you want to update. Properties that are not specified in BrowserExtTabUpdateDetails are not modified. This is an asynchronous function that returns a Promise.
BrowserExtTabsAPI
The interface for the browser.tabs object.
tabs
The browser.tabs object.

The webNavigation object

Overview

The webNavigation object is used to monitor events related to networking requests.

Manifest

The "webNavigation" permission is required to use this object.

{
    "permissions": [                               // Required
        "webNavigation"                            // Required
    ]                                              // Required   
}

Context

This API is available in Window context (background, event, popup, options and custom pages).

WebIDL Definition

A description of the special WebIDL syntax considerations for browser extensions are defined elsewhere in this document.

enum BrowserExtTransitionType { "link", "typed" };
dictionary BrowserExtWebNavigationOnBeforeNavigateDetails {
    long frameId;
    long parentFrameId;
    long tabId;
    double timeStamp;
    DOMString url;
};
dictionary BrowserExtWebNavigationOnCommittedDetails {
    long frameId;
    long processId;
    long tabId;
    double timeStamp;
    TransitionType transitionType;
    DOMString url;
};
dictionary BrowserExtWebNavigationOnCompletedDetails {
    long frameId;
    long processId;
    long tabId;
    double timeStamp;
    DOMString url;
};
dictionary BrowserExtWebNavigationOnDOMContentLoadedDetails {
    long frameId;
    long processId;
    long tabId;
    double timeStamp;
    DOMString url;
};
dictionary BrowserExtWebNavigationOnErrorOccurredDetails {
    DOMString error;
    long frameId;
    long tabId;
    double timeStamp;
    DOMString url;
};
dictionary BrowserExtWebNavigationOnReferenceFragmentUpdatedDetails {
    long frameId;
    long processId;
    long tabId;
    double timeStamp;                           
    BrowserExtTransitionType transitionType;
    DOMString url;
};
callback BrowserExtWebNavigationOnBeforeNavigateCallback = void (BrowserExtWebNavigationOnBeforeNavigateDetails details);
callback BrowserExtWebNavigationOnCommittedCallback = void (BrowserExtWebNavigationOnCommittedDetails details);
callback BrowserExtWebNavigationOnCompletedCallback = void (BrowserExtWebNavigationOnCompletedDetails details);
callback BrowserExtWebNavigationOnDOMContentLoadedCallback = void (BrowserExtWebNavigationOnDOMContentLoadedDetails details);
callback BrowserExtWebNavigationOnErrorOccurredCallback = void (BrowserExtWebNavigationOnErrorOccurredDetails details);
callback BrowserExtWebNavigationOnReferenceFragmentUpdated = void (BrowserExtWebNavigationOnReferenceFragmentUpdatedDetails details);
[NoInterfaceObject]
interface BrowserExtBrowserWebNavigation {
    void onBeforeNavigate(BrowserExtWebNavigationOnBeforeNavigateCallback callback);
    void onCommitted(BrowserExtWebNavigationOnCommittedCallback callback);
    void onCompleted(BrowserExtWebNavigationOnCompletedCallback callback);
    void onDOMContentLoaded(BrowserExtWebNavigationOnDOMContentLoadedCallback callback);
    void onErrorOccurred(BrowserExtWebNavigationOnErrorOccurredCallback callback);
    void onReferenceFragmentUpdated(BrowserExtWebNavigationOnReferenceFragmentUpdated callback);
};
    
[NoInterfaceObject, Exposed=Window, CheckAnyPermissions_browserExtWebNavigation_]
interface BrowserExtWebNavigationAPI {
    readonly attribute BrowserExtWebNavigation webNavigation; 
};
Browser implements BrowserExtWebNavigationAPI;

Definitions

BrowserExtTransitionType
Cause of the navigation. For example, the user clicked a link or typed an address.
link
The user clicked a link in another page.
typed
The user typed the URL into the address bar. This is also used if the user started typing into the address bar, then selected a URL from the suggestions it offered.
BrowserExtWebNavigationOnBeforeNavigateDetails
Information provided to the webNavigation.onBeforeNavigate callback.
frameId
integer. Frame in which the navigation is about to occur. 0 indicates that navigation happens in the tab's top-level browsing context, not in a nested iframe. A positive value indicates that navigation happens in a nested iframe. Frame IDs are unique for a given tab and process.
parentFrameId
integer. ID of this frame's parent. Set to -1 if this is a top-level frame.
tabId
integer. The ID of the tab in which the navigation is about to occur.
timeStamp
number. The time when the browser is about to start the navigation, in milliseconds since the epoch.
url
string. The URL to which the given frame will navigate.
BrowserExtWebNavigationOnCommittedDetails
Information provided to the webNavigation.onCommitted callback.
frameId
integer. Frame in which the navigation will occur. 0 indicates that navigation happens in the tab's top-level browsing context, not in a nested iframe. A positive value indicates that navigation happens in a nested iframe. Frame IDs are unique for a given tab and process.
processId
integer. The ID of the process in which this tab is being rendered.
tabId
integer. The ID of the tab in which the navigation is about to occur.
timeStamp
number. The time that the navigation was committed, in milliseconds since the epoch.
transitionType
The reason for the navigation: for example, "link" if the user clicked a link, or "reload" if the user reloaded the page.
url
string. The URL to which the given frame will navigate.
BrowserExtWebNavigationOnCompletedDetails
Information provided to the webNavigation.onCompleted callback.
frameId
integer. Frame in which the navigation has occurred. 0 indicates that navigation happened in the tab's top-level browsing context, not in a nested iframe. A positive value indicates that navigation happened in a nested iframe. Frame IDs are unique for a given tab and process.
processId
integer. The ID of the process in which this tab is being rendered.
tabId
integer. The ID of the tab in which the navigation has occurred.
timeStamp
number. The time at which the page finished loading, in milliseconds since the epoch.
url
string. The URL to which the given frame has navigated.
BrowserExtWebNavigationOnDOMContentLoadedDetails
Information provided to the webNavigation.onDOMContentLoaded callback.
frameId
integer. Frame in which the navigation is occurring. 0 indicates that navigation happens in the tab's top-level browsing context, not in a nested iframe. A positive value indicates that navigation happens in a nested iframe. Frame IDs are unique for a given tab and process.
processId
integer. The ID of the process in which this tab is being rendered.
tabId
integer. The ID of the tab in which the navigation has occurred.
timeStamp
number. The time at which DOMContentLoaded was fired, in milliseconds since the epoch.
url
string. The URL to which the given frame has navigated.
BrowserExtWebNavigationOnErrorOccurredDetails
Information provided to the webNavigation.onErrorOccurred callback.
error
string. The error code. This is an internal error code, and is not guaranteed to stay the same or be consistent from one browser to another.
frameId
integer. Frame in which the navigation is occurring. 0 indicates that navigation happens in the tab's top-level browsing context, not in a nested iframe. A positive value indicates that navigation happens in a nested iframe. Frame IDs are unique for a given tab and process.
tabId
integer. The ID of the tab in which the navigation has occurred.
timeStamp
number. The time at which DOMContentLoaded was fired, in milliseconds since the epoch.
url
string. The URL to which the given frame has navigated.
BrowserExtWebNavigationOnReferenceFragmentUpdatedDetails
Information provided to the webNavigation.onReferenceFragmentUpdated callback.
frameId
integer. Frame in which the navigation will occur. 0 indicates that navigation happens in the tab's top-level browsing context, not in a nested iframe. A positive value indicates that navigation happens in a nested iframe. Frame IDs are unique for a given tab and process.
processId
integer. The ID of the process in which this tab is being rendered.
tabId
integer. The ID of the tab in which the navigation is about to occur.
timeStamp
number. The time that the navigation was committed, in milliseconds since the epoch.
transitionType
transitionType. The reason for the navigation: for example, "link" if the user clicked a link
url
string. The URL to which the given frame will navigate.
BrowserExtWebNavigationOnBeforeNavigateCallback
The webNavigation.onBeforeNavigate callback.
BrowserExtWebNavigationOnCommittedCallback
The webNavigation.onCommittedCallback callback.
BrowserExtWebNavigationOnCompletedCallback
The webNavigation.onCompletedCallback callback.
BrowserExtWebNavigationOnDOMContentLoadedCallback
The webNavigation.onDOMContentLoadedCallback callback.
BrowserExtWebNavigationOnErrorOccurredCallback
The webNavigation.onErrorOccurredCallback callback.
BrowserExtWebNavigationOnReferenceFragmentUpdated
The webNavigation.onReferenceFragmentUpdated callback.
BrowserExtBrowserWebNavigation
The definition for the browser.webNavigation object.
onBeforeNavigate
Fired when the browser is about to start a navigation event.
onCommitted
Fired when a navigation is committed. At least part of the new document has been received from the server and the browser has decided to switch to the new document.
onCompleted
Fired when a document, including the resources it refers to, is completely loaded and initialized. This is equivalent to the DOM load event.
onDOMContentLoaded
Fired when the DOMContentLoaded event is fired in the page. At this point the document is loaded and parsed, and the DOM is fully constructed, but linked resources such as images, stylesheets and subframes may not yet be loaded.
onErrorOccurred
Fired when an error occurs and the navigation is aborted. This can happen if either a network error occurred, or the user aborted the navigation.
onReferenceFragmentUpdated
Fired if the fragment identifier for a page is changed. For example, if a page implements a table of contents using fragments, and the user clicks an entry in the table of contents, this event will fire. All future events for this frame will use the updated URL.

BrowserExtWebNavigationAPI
The interface for the browser.webNavigation object.
webNavigation
The browser.webNavigation object.

The webRequest object

Overview

The webRequest object is used to modify or cancel networking requests.

Manifest

The "webRequest" permission is required to use this object.

{
    "permissions": [                           // Required
        "webRequest"                            // Required
        "webRequestBlocking"                    // Optional
        "<URL pattern>"                         // Optional, e.g. "*://*.w3.org/"
    ]                                          // Required   
}

Context

This API is available in Window context (background, event, popup, options and custom pages).

WebIDL Definition

A description of the special WebIDL syntax considerations for browser extensions are defined elsewhere in this document.

enum BrowserExtResourceType { "font", "image", "main_frame", "object", "other", "ping", "script", "stylesheet", "sub_frame", "xmlhttprequest" };
dictionary BrowserExtWebRequestUploadDetails {
    any bytes;
    DOMString? file;
};
dictionary BrowserExtWebRequestRequestBody {
    DOMString? error;
    object? formData;
    sequence<BrowserExtWebRequestUploadData>? rawData;
};
dictionary BrowserExtWebRequestHttpHeader {
    DOMString keyName;
    any value;
};
dictionary BrowserExtWebRequestHttpHeaders {
    sequence<BrowserExtWebRequestHttpHeader> data; 
};
dictionary BrowserExtWebRequestOnBeforeRequestDetails {
    long frameId;
    DOMString method;
    long parentFrameId;
    BrowserExtWebRequestRequestBody? requestBody;
    DOMString requestId;
    long tabId;
    double timeStamp;
    BrowserExtResourceType type;
    DOMString url;
};
dictionary BrowserExtWebRequestOnBeforeSendHeadersDetails {
    long frameId;
    DOMString method;
    long parentFrameId;
    BrowserExtWebRequestHttpHeaders? requestHeaders;
    DOMString requestId;
    long tabId;
    double timeStamp;
    BrowserExtResourceType type;
    DOMString url;
};
dictionary BrowserExtWebRequestOnCompletedDetails {
    long frameId;
    boolean fromCache;
    DOMString method;
    long parentFrameId;
    DOMString requestId;
    BrowserExtWebRequestHttpHeaders? responseHeaders;
    DOMString? serverIP;
    long statusCode;
    DOMString statusLine;
    long tabId;
    double timeStamp;   
    BrowserExtResourceType type;
    DOMString url;
}; 
dictionary BrowserExtWebRequestOnHeadersReceivedDetails {
    long frameId;
    DOMString method;
    long parentFrameId;
    DOMString requestId;
    BrowserExtWebRequestHttpHeaders? responseHeaders;
    long statusCode;
    DOMString statusLine;
    long tabId;
    double timeStamp;   
    BrowserExtResourceType type;
    DOMString url;
};
dictionary BrowserExtWebRequestOnSendHeadersDetails {
    long frameId;
    DOMString method;
    long parentFrameId;
    BrowserExtWebRequestHttpHeaders? requestHeaders;
    DOMString requestId;
    long tabId;
    double timeStamp;   
    BrowserExtResourceType type;
    DOMString url;
};
callback BrowserExtWebRequestOnBeforeRequestCallback = void (BrowserExtWebRequestOnBeforeRequestDetails details);
callback BrowserExtWebRequestOnBeforeSendHeadersCallback = void (BrowserExtWebRequestOnBeforeSendHeadersDetails details);
callback BrowserExtWebRequestOnCompletedCallback = void (BrowserExtWebRequestOnCompletedDetails details);
callback BrowserExtWebRequestOnHeadersReceivedCallback = void (BrowserExtWebRequestOnHeadersReceivedDetails details);
callback BrowserExtWebRequestOnSendHeadersCallback = void (BrowserExtWebRequestOnSendHeadersDetails details);
[NoInterfaceObject]
interface BrowserExtBrowserWebRequest {
    void onBeforeRequest(BrowserExtWebRequestOnBeforeRequestCallback callback);
    void onBeforeSendHeaders(BrowserExtWebRequestOnBeforeSendHeadersCallback callback);
    void onCompleted(BrowserExtWebRequestOnCompletedCallback callback);
    void onHeadersReceived(BrowserExtWebRequestOnHeadersReceivedCallback callback);
    void onSendHeaders(Function callback);
};
[NoInterfaceObject, Exposed=Window, CheckAnyPermissions_browserExtWebRequest_]
interface BrowserExtWebRequestAPI {
    readonly attribute BrowserExtWebRequest webRequest; 
};
Browser implements BrowserWebRequestAPI;

Definitions

BrowserExtResourceType
This type is a string, which represents a particular kind of resource fetched in a web request. It's used to filter the requests you listen to using the webRequest API. For example: you can listen to requests only for images, or only for scripts.
font
Fire browser.webRequest events for font requests.
image
Fire browser.webRequest events for image requests.
main_frame
Fire browser.webRequest events for main frame requests.
object
Fire browser.webRequest events for object requests.
other
Fire browser.webRequest events for requests of a type not declared here.
ping
Fire browser.webRequest events for ping requests.
script
Fire browser.webRequest events for script requests.
stylesheet
Fire browser.webRequest events for stylesheet requests.
sub_frame
Fire browser.webRequest events for subframe requests.
xmlhttprequest
Fire browser.webRequest events for xmlhttprequest requests.
BrowserExtWebRequestUploadDetails
Contains data uploaded in a URL request.
bytes
any. An ArrayBuffer with a copy of the data.
file
string. A string with the file's path and name
BrowserExtWebRequestRequestBody
object. Contains the HTTP request body data.
error
string. This is set if any errors were encountered when obtaining request body data.
formData
object. This object is present if the request method is POST and the body is a sequence of key-value pairs encoded in UTF-8 as either "multipart/form-data" or "application/x-www-form-urlencoded".
rawData
array of webRequest.UploadData. If the request method is PUT or POST, and the body is not already parsed in formData, then this array contains the unparsed request body elements.
BrowserExtWebRequestHttpHeader
Each header is represented as an object with two properties: name and value.
keyName
string. Name of the HTTP header.
value
string. Value of the HTTP header if it can be represented by UTF-8.
BrowserExtWebRequestHttpHeaders
An array of HTTP headers.
data
The HTTP header data.
BrowserExtWebRequestOnBeforeRequestDetails
Information about the request.
frameId
integer. Zero if the request happens in the main frame; a positive value is the ID of a subframe in which the request happens. If the document of a (sub-)frame is loaded (type is main_frame or sub_frame), frameId indicates the ID of this frame, not the ID of the outer frame. Frame IDs are unique within a tab.
method
string. Standard HTTP method: for example, "GET" or "POST".
parentFrameId
integer. ID of the frame that contains the frame which sent the request. Set to -1 if no parent frame exists.
requestBody
Contains the HTTP request body data.
requestId
string. The ID of the request. Request IDs are unique within a browser session, so you can use them to relate different events associated with the same request.
tabId
integer. ID of the tab in which the request takes place. Set to -1 if the request isn't related to a tab.
timeStamp
number. The time when this event fired, in milliseconds since the epoch.
type
The type of resource being requested: for example, "image", "script", "stylesheet".
url
string. URL of the resource that triggered this request. Note that this may not be the same as the URL of the page into which the requested resource will be loaded. For example, if a document triggers a load in a different window through the target attribute of a link, or a CSS document includes an image using the url() functional notation, then this will be the URL of the original document or of the CSS document, respectively.
BrowserExtWebRequestOnBeforeSendHeadersDetails
Information about the request.
frameId
integer. Zero if the request happens in the main frame; a positive value is the ID of a subframe in which the request happens. If the document of a (sub-)frame is loaded (type is main_frame or sub_frame), frameId indicates the ID of this frame, not the ID of the outer frame. Frame IDs are unique within a tab.
method
string. Standard HTTP method: for example, "GET" or "POST".e
parentFrameId
integer. ID of the frame that contains the frame which sent the request. Set to -1 if no parent frame exists.
requestHeaders
The HTTP request headers that will be sent with this request.
requestId
string. The ID of the request. Request IDs are unique within a browser session, so you can use them to relate different events associated with the same request.
tabId
integer. ID of the tab in which the request takes place. Set to -1 if the request isn't related to a tab.
timeStamp
number. The time when this event fired, in milliseconds since the epoch.
type
The type of resource being requested: for example, "image", "script", "stylesheet".
url
string. Target of the request.
BrowserExtWebRequestOnCompletedDetails
Information about the request.
frameId
integer. Zero if the request happens in the main frame; a positive value is the ID of a subframe in which the request happens. If the document of a (sub-)frame is loaded (type is main_frame or sub_frame), frameId indicates the ID of this frame, not the ID of the outer frame. Frame IDs are unique within a tab.
fromCache
boolean. Indicates if this response was fetched from disk cache.
method
string. Standard HTTP method: for example, "GET" or "POST".
parentFrameId
integer. ID of the frame that contains the frame which sent the request. Set to -1 if no parent frame exists.
requestId
string. The ID of the request. Request IDs are unique within a browser session, so you can use them to relate different events associated with the same request.
responseHeaders
The HTTP response headers that were received along with this response.
serverIP
The server IP address that the request was actually sent to. Note that it may be a literal IPv6 address.
statusCode
integer. Standard HTTP status code returned by the server.
statusLine
string. HTTP status line of the response or the 'HTTP/0.9 200 OK' string for HTTP/0.9 responses (i.e., responses that lack a status line) or an empty string if there are no headers.
tabId
integer. The ID of the tab in which the request takes place. Set to -1 if the request isn't related to a tab.
timeStamp
number. The time when this event fired, in milliseconds since the epoch.
type
The type of resource being requested: for example, "image", "script", "stylesheet".
url
string. Target of the request.
BrowserExtWebRequestOnHeadersReceivedDetails
Information about the request.
frameId
integer. Zero if the request happens in the main frame; a positive value is the ID of a subframe in which the request happens. If the document of a (sub-)frame is loaded (type is main_frame or sub_frame), frameId indicates the ID of this frame, not the ID of the outer frame. Frame IDs are unique within a tab
method
string. Standard HTTP method: for example, "GET" or "POST".
parentFrameId
integer. ID of the frame that contains the frame which sent the request. Set to -1 if no parent frame exists.
requestId
string. The ID of the request. Request IDs are unique within a browser session, so you can use them to relate different events associated with the same request.
responseHeaders
The HTTP response headers that were received for this request.
statusCode
integer. Standard HTTP status code returned by the server.
statusLine
string. HTTP status line of the response or the 'HTTP/0.9 200 OK' string for HTTP/0.9 responses (that is, responses that lack a status line).
tabId
integer. ID of the tab in which the request takes place. Set to -1 if the request isn't related to a tab.
timeStamp
number. The time when this event fired, in milliseconds since the epoch.
type
The type of resource being requested: for example, "image", "script", "stylesheet".
url
string. Target of the request.
BrowserExtWebRequestOnSendHeadersDetails
Information about the request.
frameId
integer. Zero if the request happens in the main frame; a positive value is the ID of a subframe in which the request happens. If the document of a (sub-)frame is loaded (type is main_frame or sub_frame), frameId indicates the ID of this frame, not the ID of the outer frame. Frame IDs are unique within a tab.
method
string. Standard HTTP method: for example, "GET" or "POST".
parentFrameId
integer. ID of the frame that contains the frame which sent the request. Set to -1 if no parent frame exists.
requestHeaders
The HTTP request headers that have been sent out with this request.
requestId
string. The ID of the request. Request IDs are unique within a browser session, so you can use them to relate different events associated with the same request.
tabId
integer. ID of the tab in which the request takes place. Set to -1 if the request isn't related to a tab.
timeStamp
number. The time when this event fired, in milliseconds since the epoch.
type
The type of resource being requested: for example, "image", "script", "stylesheet".
url
URL of the resource that triggered this request. Note that this may not be the same as the URL of the page into which the requested resource will be loaded. For example, if a document triggers a load in a different window through the target attribute of a link, or a CSS document includes an image using the url() functional notation, then this will be the URL of the original document or of the CSS document, respectively.
BrowserExtWebRequestOnBeforeRequestCallback
The webRequest.onBeforeRequestCallback callback.
BrowserExtWebRequestOnBeforeSendHeadersCallback
The webRequest.onBeforeSendHeadersCallback callback.
BrowserExtWebRequestOnCompletedCallback
The webRequest.onCompletedCallback callback.
BrowserExtWebRequestOnHeadersReceivedCallback
The webRequest.onHeadersReceivedCallback callback.
BrowserExtWebRequestOnSendHeadersCallback
The webRequest.onSendHeadersCallback callback.
BrowserExtBrowserWebRequest
The description for the browser.webRequest object.
onBeforeRequest
This event is triggered when a request is about to be made, and before headers are available. This is a good place to listen if you want to cancel or redirect the request.
onBeforeSendHeaders
This event is triggered before sending any HTTP data, but after all HTTP headers are available. This is a good place to listen if you want to modify HTTP request headers.
onCompleted
Fired when a request has completed.
onHeadersReceived
Fired when the HTTP response headers associated with a request have been received. You can use this event to modify HTTP response headers.
onSendHeaders
This event is fired just before sending headers. If your extension or some other extension modified headers in onBeforeSendHeaders, you'll see the modified version here.
BrowserExtWebRequestAPI
The interface for the browser.webRequest object.
webRequest
The browser.webRequest object.

The windows object

Overview

The windows object is used to access the UI windows managed by the browser.

Manifest

There are no additional manifest entries required for an extension to use this object.

Context

This API is available in Window context (background, event, popup, options and custom pages).

WebIDL Definition

A description of the special WebIDL syntax considerations for browser extensions are defined elsewhere in this document.

enum BrowserExtWindowsWindowType { "detached_panel", "normal", "panel", "popup" };
enum BrowserExtWindowsWindowState { "docked", "fullscreen", "maximized", "minimized", "normal" };
dictionary BrowserExtCreateWindowDetails {
    boolean focused;
    long height;
    boolean incognito;
    long left;
    BrowserExtWindowsWindowState? state;
    long tabId;
    long top;
    (DOMString? or sequence<DOMString>?) url;
    long width;
    BrowserExtWindowsWindowType? windowType;
};
dictionary BrowserExtGetWindowDetails {
    boolean populate;
    sequence<BrowserExtWindowsWindowType>? windowTypes;
};
dictionary BrowserExtWindowUpdateDetails {
    boolean drawAttention;
    boolean focused;
    long height;
    long left;
    long top;
    long width;
    BrowserExtWindowState? windowState;
};
dictionary BrowserExtWindowsWindow {
    boolean alwaysOnTop;
    boolean focused;
    long height;
    long id;
    boolean incognito;
    long left;
    sequence<BrowserExtTabsTab>? tabs;
    long top;
    DOMString? sessionId;
    BrowserExtWindowsWindowState? state;
    long width;
    BrowserExtWindowsWindowType? windowType;
};
callback BrowserExtWindowsOnFocusChangedCallback = void (long windowId);
[NoInterfaceObject]
interface BrowserExtWindows {
    Promise<BrowserExtWindowsWindow> create(CreateWindowDetails details);
    Promise<BrowserExtWindowsWindow> get(long windowId, optional BrowserExtGetWindowDetails details);
    Promise<sequence<BrowserExtWindowsWindow>> getAll(optional BrowserExtGetWindowDetail details);
    Promise<BrowserExtWindowsWindow> getCurrent(optional BrowserExtGetWindowDetail details);
    Promise<BrowserExtWindowsWindow> getLastFocused(optional BrowserExtGetWindowDetail details);
    void onFocusChanged(BrowserExtWindowsOnFocusChangedCallback callback);
    Promise<BrowserExtWindowsWindow> update(long windowId, optional BrowserExtWindowUpdateDetails details);
};
    
[NoInterfaceObject, Exposed=Window, CheckAnyPermissions_browserExt_]
interface BrowserExtWindowsAPI {
readonly attribute BrowserExtWindows windows; 
};
Browser implements BrowserExtWindowsAPI;

Definitions

BrowserExtWindowsWindowType
The type of browser window this is.
detached_panel
The browser window is a detached panel.
normal
The browser window is a normal window.
panel
The browser window is a panel.
popup
The browser window is a popup.
BrowserExtWindowsWindowState
The state of this browser window.
docked
The window is docked.
fullscreen
The window is full screen.
maximized
The window is maximized.
minimized
The window is minimized.
normal
The window is normal.
BrowserExtCreateWindowDetails
Information about a browser window.
focused
boolean. Whether the window is currently the focused window.
height
integer. The height of the window, including the frame, in pixels.
incognito
boolean. Whether the window is incognito.
left
integer. The offset of the window from the left edge of the screen in pixels.
state
Represents the state of this browser window — maximized, minimized, etc.
tabId
integer. The ID of the tab.
top
integer. The offset of the window from the top edge of the screen in pixels.
url
string or array of strings. A URL or array of URLs to open as tabs in the window. Fully-qualified URLs must include a scheme. Relative URLs will be relative to the current page within the extension.
width
integer. The width of the window, including the frame, in pixels.
windowType
Represents the type of browser window — normal browser window, popup, etc.
BrowserExtGetWindowDetails
Details about a window, given its ID.
populate
boolean. If true, the windows.Window object will have a tabs property that contains a list of tabs.Tab objects representing the tabs open in the window. The Tab objects only contain the url, title and favIconUrl properties if the extension's manifest file includes the "tabs" permission.
windowTypes
array of BrowserExtWindowsWindowType
BrowserExtWindowUpdateDetails
Object containing the properties to update.
drawAttention
boolean. If true, causes the window to be displayed in a manner that draws the user's attention to the window, without changing the focused window. The effect lasts until the user changes focus to the window. This option has no effect if the window already has focus. Set to false to cancel a previous drawAttention request.
focused
boolean. If true, brings the window to the front. If false, brings the next window in the z-order to the front.
height
integer. The height to resize the window to in pixels. This value is ignored for panels.
left
integer. The offset from the left edge of the screen to move the window to in pixels. This value is ignored for panels.
top
integer. The offset from the top edge of the screen to move the window to in pixels. This value is ignored for panels.
width
integer. The width to resize the window to in pixels. This value is ignored for panels.
windowState
The new state of the window. The minimized, maximized and fullscreen states cannot be combined with left, top, width or height.
BrowserExtWindowsWindow
Information about a browser window.
alwaysOnTop
boolean. Whether the window is set to be always on top.
focused
boolean. Whether the window is currently the focused window.
height
integer. The height of the window, including the frame, in pixels
id
integer. The ID of the window. Window IDs are unique within a browser session.
incognito
boolean. Whether the window is incognito.
left
integer. The offset of the window from the left edge of the screen in pixels.
tabs
Array of tabs.Tab objects representing the current tabs in the window.
top
integer. The offset of the window from the top edge of the screen in pixels.
sessionId
string. The session ID used to uniquely identify a Window.
state
Represents the state of this browser window — maximized, minimized, etc.
width
integer. The width of the window, including the frame, in pixels.
windowType
Represents the type of browser window this is — normal browser window, popup, etc.
BrowserExtWindowsOnFocusChangedCallback
The browser.windows.onFocusChanged callback.
BrowserExtWindows
The definition for the browser.windows object.
create
Creates a new window.
get
Gets details about a window, given its ID. The details are passed into a callback. This is an asynchronous function that returns a Promise.
getAll
Gets information about all open windows, passing them into a callback. This is an asynchronous function that returns a Promise.
getCurrent
Gets the current window, passing its details into a callback. This is an asynchronous function that returns a Promise.
getLastFocused
Gets the window that was most recently focused — typically the window 'on top' — and passes it into a callback. This is an asynchronous function that returns a Promise.
onFocusChanged
Fired when the currently focused window changes. Will be windows.WINDOW_ID_NONE if all browser windows have lost focus.
update
Updates the properties of a window. Use this to move, resize, and (un)focus a window, etc. This is an asynchronous function that returns a Promise.
BrowserExtWindowsAPI
The interface for the browser.windows object.
windows
The browser.windows object.

Native Messaging

Native Messaging is covered in another specification. Refer to the Native Messaging for Browser Extensions specification [[browserext-native]] for more information.

Events

Overview

Extension events are similar to DOM Events [DOM4]. However, extension events are dispatched only to objects in the relevant extension scope (background, event, options, content, etc.). Script in the extension scope can observe events by calling addListener().

[NoInterfaceObject, Exposed=(Window,ContentScript), CheckAnyPermissions_browserExt_]
interface BrowserExtEvent {
    void    addListener(Function callback);
    void    removeListener(Function callback);
    boolean hasListener(Function callback);
    boolean hasListeners();
};

Definitions

BrowserExtEvent
The Event type used by extensions
addListener
Register to be notified when the even fires.
removeListener
Unregister for notifications.
hasListener
Confirms whether a specific listener has been registered.
hasListeners
Confirms whether any listeners have been registered.

Message Strings

Overview

Message strings are used in the manifest.json file as well browser.i18n.getMessage().

Predefined messages

Predefined messages are accessed in the same way as other messages. The syntax for standard messages is:

__MSG_extensionName__

Predefined messages use exactly the same syntax, except with @@ before the message name. For example:

__MSG_@@ui_locale__

The following table shows the different available predefined messages:

Message nameDescription
@@extension_idThe extension or app ID; you might use this string to construct URLs for resources inside the extension. Even unlocalized extensions can use this message. Note that you can't use this message in a manifest file.
@@ui_localeThe current locale; you might use this string to construct locale-specific URLs.
@@bidi_dirThe text direction for the current locale, either "ltr" for left-to-right languages such as English or "rtl" for right-to-left languages such as Arabic.
@@bidi_reversed_dirIf the @@bidi_dir is "ltr", then this is "rtl"; otherwise, it's "ltr".
@@bidi_start_edgeIf the @@bidi_dir is "ltr", then this is "left"; otherwise, it's "right".
@@bidi_end_edgeIf the @@bidi_dir is "ltr", then this is "right"; otherwise, it's "left".

Manifest Format

Pre-parsing

Standards-compliant browsers are expected to ignore "//" comments. Disregarding comments, the manifest.json file format for browser extensions is expected to be fully JSON compliant. Malformed JSON files are not supported. If manifest keys that are not defined in this specification are specified, other browsers MAY ignore those keys.

List of Keys

The full list of supported manifest keys is provided below:

KeyRequiredDetails
"name"RequiredThe name of the extension.
"version"RequiredA string representation of a number
"default_locale"Required if extension uses locales. Not allowed if extension does not use localesSee Message Strings and browser.i18n for more information about the use of locales and localized resources.
"description"OptionalDescribes the capabilities of the extension.
"icons" : {
   "<size>" : "<filename.jpg>"
}
OptionalA list of pairs of pixel dimensions and JPEG filenames. These are typically used to display visuals for the extension in browser management UI for extensions. Browsers MAY require specific sizes. For example,
"icons":{
   "16":"small.jpg",
   "32":"medium.jpg"
}
would be used for a small JPEG with height of 16 pixels and width of 16 pixels (small.jpg), and a second JPEG 32x32 pixels in size (medium.jpg).
"developer": {
   "name": "<Company>",
   "url": "<Website>"
}
OptionalIncludes subkeys for "name" and "url" that provide information about the entity that authored the extension, typically a company or programmer name. The "url" subkey SHOULD refer to the company/programmer site, not a description of the extension.
"browser_action"Optional

Note that some browsers only permit "browser_action" or "page_action", but not both at the same time

See browser.browserAction for more information about the subkeys for "browser_action".
"page_action"Optional

Note that some browsers only permit "browser_action" or "page_action", but not both at the same time
See browser.pageAction for more information about the subkeys for "page_action".
"browser_specific_settings":{
   <browser_name>": {
   "   "<key>": "<value>"
   }
}
OptionalDescribes specific values that MAY be considered by a browser. For example, a particular extension may require version 42 or greater of the Gecko browser in order to work properly:
"browser_specific_settings":{
   "gecko": {
      "strict_min_version": "42.0"
   }
}

"background" : {
   "page": "<Page URL>",
   "scripts": [...],
   "persistent": boolean,
}
Optional

If "background" is specified, "persistent" is required.

Other subkeys are optional
Automatically loads a page or script and begins execution, regardless of the page being viewed in a tab.
"content_scripts" : {
   "all_frames": <boolean>,
   "css": [...],
   "exclude_matches": [...],
   "js": [...],
   "matches": [...],
   "run_at": <see_details>,
}
OptionalAutomatically adds scripts (from the "js" subkey list) or CSS (from the "css" subkey list) to each page within a tab.

If all_frames is false, the string patterns from matches and exclude_matches are used accordingly to determine which page content is modified or excluded.

Valid values for "run_at" are "document_start", "document_end" and "document_idle".

"content_security_policy"OptionalA string representation of the new policy to override the default policy. See Content Security Policy (CSP) for more information.
"options_page"OptionalThe page within the extension that allows extension users to modify settings or options for the extension.
"manifest_version"OptionalThis is not used
"required_keys":[...]OptionalSee the required_keys key section for more information about this key.
"web_accessible_resources":[...]OptionalResources listed here may be accessed by Internet-hosted site pages.
"externally_connectable": [
   "ids": [...],
   "matches": [...],
]
OptionalOther extensions or Internet-hosted site pages may send messages to this extension if their extension ID ("ids") or page URL pattern ("matches") are specified.
"permissions" : {
   "activeTab",
   "contextMenus",
   "tabs",
   "webNavigation",
   "webRequestBlocking",
   "<url-pattern>",
}
Optional Each subkey must be specified in order to use the associated API.
Patterns listed in <url-pattern> allow additional permissions for URLs that match those patterns. See Permissions URL patterns for more information.

Permissions URL patterns

The "permissions" key may include match patterns that follow the structure <scheme>://<host>/<path>, such as "*://*.w3.org/*". The special pattern "<all_urls>" is also permitted. The match patterns identify a group of URLs for which the extension is requesting extra privileges:

The activeTab permission

The "activeTab" permission enables the use of browser.tabs API only if the user has actively initiated an action such as the browserAction. The browser.tabs API can be used until the tab is navigated to another page or closed.

Passive background-only extensions cannot use the browser.tabs API unless both the "tabs" permission and a URL pattern (e.g. "<all_urls>" or "http://*" or "*://&.w3.org/*") are explicitly declared in manifest.json.

The required_keys key

This key is optional, but if it is specified, it provides a list of strings representing manifest keys that MUST be supported. If the browser loading the extension does not support the specified key, the browser MUST reject the manifest and not load the extension.

Full Example

// Standards-compliant browsers are expected to ignore "//" comments. Disregarding comments, 
// the manifest.json file format for browser extensions is expected to be fully JSON compliant. 
// Malformed JSON files are not supported.
//
// Other manifest keys that are well-formed JSON but are not listed here MUST be ignored.
//
// Note that some fields marked as Optional here are required by vendor-specific distribution Stores.
{
  "name": "The Name of Your Extension",             // Required
  "version": "Your Extension Version",              // Required
  "default_locale": "en",                           // Required if locales are used. Otherwise, not allowed
  "description": "Description for Your Extension",   
  "icons": {...},                                    
  "developer": {                                    
       "name": "Your Name or Company",              
       "url": "Company Website"                      
  }
  // Note: Some browsers require an extension to use either browser_action or page_action, but not both simultaneously
  "browser_action": {  
      "default_icon": {...},                        // Same format as "icons"
      "default_popup": "Page URL",
      "default_title": "Title string"
  },
  "page_action": {...},                             // Same format as "browser_action"
  
  "browser_specific_settings": {                    
       "<browser_name>": {                          // Examples "gecko","opera","edge"
            "<key>": "<value>"                      // Examples "strict_min_version": "42.0", "id": "addon@example.com"
       }
  },
  "background": {                                   
      "page": "Page URL",                           // Only one of "page" or "scripts" is supported, but not both simultaneously
      "scripts": [],                                // Only one of "page" or "scripts" is supported, but not both simultaneously
      "persistent": false                           // Required if "background" is specified
  },
  "content_scripts": {                                                    
      "all_frames": false,                          
      "css": [],                                   
      "exclude_matches": [],                        
      "js": [],                                     
      "matches": [],                                
      "run_at" : "document_start"                   // Also "document_end", "document_idle"
  }
  "content_security_policy": "<policy-string>",     
  
  "options_page": "Page URL",                            // Optional
  "manifest_version": 2,                            // Not used
  "required_keys": [],                              // If a browser does not recognize a key in this list, it MUST 
                                                    // reject the manifest (e.g. "sidebar_action")
                                                    // FEEDBACK: Rename to "required_capabilities"
  "permissions": {                                  
       "activeTab",                                                
       "contextMenus",                              
       "tabs",                                      
       "webNavigation",                            
       "webRequest",                                
       "webRequestBlocking",                        
       "<url-pattern>"                              // Examples "http://*/*", "<all_urls>"
  },
  "web_accessible_resources": [...]    
  "externally_connectable" : [
       "ids":[...], // Identifiers for other extensions that are allowed to send messages
       "matches":[...] // URL patterns for hosted web pages allowed to send messages 
  ]                             
}

Extension Resources

The browserext:// protocol

To access resources within the extension, such as browserext://<ext_id>/options.html, the browserext:// protocol is used.

Extension IDs

Each extension has an extension ID that follows the browserext:// protocol. For example

browserext://MyExtension_c1wakc4j0nefm/options.html browserext://dfcijpibodeoenkablikbkiobbdnkfki/options.html

The algorithms that generate these IDs are different for each browser. To access these resources, do not hardcode the ID generated by a particular browser. Instead, use the runtime.getURL() method to convert a relative file name or path to the absolute name or path, which includes the extension ID.

Content Security Policy (CSP)

Overview

Content Security Policy (CSP) is intended to prevent inadvertant execution of malicious code. The default CSP for web content is discussed in the specification [[CSP3]] . For extensions, the default CSP is

"script-src 'self'; object-src 'self';"

This means:

Cross-domain Privileges

Content scripts get the same cross-domain privileges as the rest of the extension. So if the extension has requested cross-domain access for a domain using the permissions key in manifest.json, then its content scripts get access that domain as well.

Content and Background Script Communication

Although content scripts can't directly use most of the extension APIs, they can communicate with the extension's background scripts using the messaging APIs, and can therefore indirectly access all the same APIs that the background scripts can.

Testing Extensions with WebDriver

Browsers vendors MAY choose to implement WebDriver support in their browsers to allow for the automated testing of browser extensions. To implement this support, the browser MUST support:

Protocol

List of Endpoints

In addition to the endpoints defined in the WebDriver specification [[webdriver]], support for browser extensions requires these additional endpoints.

Method URI Template Command
POST /session/{sessionId}/browserext Install Browser Extensions
DELETE /session/{sessionId}/browserextextensionId} Uninstall a Browser Extension
GET /session/{sessionId}/browserexts Get Browser Extensions
GET /session/{sessionId}/browserext/{extensionId}/actions Get Browser Extension Actions
POST /session/{sessionId}/browserext/{extensionId}/action/ Take Browser Extension Action
GET /session/{sessionId}/element/{element id}/browserext/contextMenuItems Get Browser Extension Context Menu Items
POST /session/{sessionId}/element/{element id}/browserext/contextMenuItem/{menuitemId} Select Browser Extension Context Menu Item
GET /session/{sessionId}/browserext/permissionPrompt Get Browser Extension Permission Prompt Text
POST /session/{sessionId}/browserext/permissionPrompt/{promptId}/action/{promptAction} Take Browser Extension Permission Prompt Action

Handling Errors

In addition to the codes defined in the Handling Errors section of the WebDriver specification [[webdriver]], support for browser extensions requires support the following additional error codes:

Error Code HTTP Status JSON Error Code Description
no such extension path 400 no such extension path The filepath specified does not point to a valid browser extension on disk.
extension not installable 400 extension not installable The specified extension could not be installed for some reason, e.g. its manifest.json is malformed or missing
no such browser extension 400 no such browser extension There is no available browser extension on the current page with the given type.
no such browser extension action 400 no such browser action A request to take a browser extension action could not be satisfied because there is no browser extension action with the given id.
no such browser extension context menu item 400 no such browser extension context menu item A request to select an extension context menu item could not be completed because there is no matching extension context menu item for the given element.
no such browser extension permission prompt 400 no such browser extension permission prompt A request to obtain the permission prompt information could not be completed because there is no permission prompt at this time or the requested prompt was not available.
no such browser extension permission prompt action 400 no such browser extension permission prompt action A request to take the specified action could not be completed because the action was not available.

Capabilities

In addition to the Capabilities defined in the WebDriver specification [[webdriver]], support for browser extensions requires the following additional entry on the server capabilities JSON object:

"enabledBrowserExtensions"
An array of absolute paths which point to the location of browser extension files. The path MUST point to either a single file appropriate for a specific brower (e.g. .crx) or a folder which contains the extension source files. If a folder is specified, the folder itself MUST contain a manifest.json file. Subfolders containing manifest.json files will not be searched.

Extension Lifetime

No browser extension will be installed or pre-loaded during a WebDriver session unless it is explicitly specified in the enabledBrowserExtensions array. Browser extensions loaded during the session will not be available to other active instances of the browser that are not part of the WebDriver session. When the session ends, the array of browser extensions are unloaded and uninstalled.

Browser Extensions Commands

Users interact with extensions through several means. First there are actions embedded in the UI of the browser, which can do something directly or open a popup. If the extension uses a popup, it can contain any html content. Finally, extensions can add items to the browser's context menu. WebDriver needs to be able to emulate user actions for all three of these controls in order to completely emulate user interaction.

In addition to the commands defined in the WebDriver specification [[webdriver]], support support for browser extensions requires the following additional commands.

installBrowserExtensions()

HTTP Method Path Template Notes
POST /session/{sessionId}/browserext

This command installs any number of specified extensions from disk at runtime

The value of the extensionPaths property MUST be an array of absolute paths which point to the location of browser extension files. The path MUST point to either a single file appropriate for a specific brower (e.g. .crx) or a folder which contains the extension source files. If a folder is specified, the folder itself MUST contain a manifest.json file. Subfolders containing manifest.json files will not be searched.

If any of the absolute paths specified in the extensionPaths property are invalid, a no such extension path status code MUST be returned.

If the installation of any extensions specified in the extensionPaths property fail, an extension not installable status code MUST be returned.

uninstallBrowserExtensions()

HTTP Method Path Template Notes
DELETE /session/{sessionId}/browserext/{extensionId}

This command uninstalls an extension in a specified browsing session.

DOMString extensionId
The unique identifier of the browser extension to be uninstalled from the session.

If the extensionId specified does not correspond to a browser extension in the current sesssion, a no such browser extension status code MUST be returned.

getBrowserExtensions()

HTTP Method Path Template Notes
GET /session/{sessionId}/browserexts

This command returns a list of all browser extensions available to the current browsing session.

  • Let extension be a new JSON Object.

  • Set the property id on extension to a string which is unique for each browser extension.

  • Set the property name on extension to a string which corresponds to the browser extension's "name" entry in manifest.json.

getBrowserExtActions()

HTTP Method Path Template Notes
GET /session/{sessionId}/browserext/{extensionId}/actions

This command returns a list of browser extension actions available for a particular browser extension. Note that this can change from page to page. It MUST return a list of objects which describes the available browser extension actions using the following algorithm for each action:

  • Let action be a new JSON Object.

  • Set the property type on action to a string which represents the type of browser extension action

  • Set the property actionTitle on action to the mouseover text for the action.

  • Set the property icon on action to the filename of the icon file or an empty string if none is displayed. If the icon is dynamically generated, the current icon MUST be returned as a lossless PNG image encoded using Base64.

  • If the action supports the badgeText property, set the property badgeText on action to the badge text displayed over the action or an empty string if none is present.

  • Return success with data action

DOMString extensionId
The unique identifier of the browser extension whose available actions are to be queried. Returned by the getBrowserExtensions() command.

If the id specified does not correspond to a browser extension in the current sesssion, a no such browser extension status code MUST be returned.

takeBrowserExtAction()

HTTP Method Path Template Notes
POST /session/{sessionId}/browserext/action/{browserExtActionId}

This command causes a browser extension action to be activated. Depending on the extensionActionType specified, this will have one of several effects:

extensionActionType Effect
browserAction This extensionActionType causes a browserAction to be activated, as if the user had clicked the browser extension's browserAction icon in the browser's chrome. Depending on the browser extension, this may cause a popup to be opened.
pageAction This extensionActionType causes a pageAction to be activated, as if the user had clicked the browser extension's pageAction icon in the browser's address bar. Depending on the browser extension, this may cause a popup to be opened.
enable This extensionActionType causes the specified extension to be enabled, as if the user had turned the extension on from the browser's management UI. If the extension is already enabled, this command has no effect.
disable This extensionActionType causes the specified extension to be disabled, as if the user had turned the extension off from the browser's management UI. If the extension is already disabled, this command has no effect.
DOMString browserExtId
The unique identifier of the browser extension whose available actions are to be invoked. Returned by the getBrowserExtensions() command.

If the extensionId specified does not correspond to a browser extension in the current sesssion, a no such browser extension status code MUST be returned.

DOMString extensionActionType
The type of the browser extension action to be taken, as returned by the getBrowserExtensionActions() command. This value SHOULD be one of the following: "pageAction", "browserAction", "enable", or "disable"

If the type specified does not correspond to a browser extension action available in the browser/on the current page, a no such browser extension action status code MUST be returned.

getBrowserExtContextMenuItems()

HTTP Method Path Template Notes
GET /session/{sessionId}/element/{elementId}/browserext/contexMenuItems

This command opens a context menu for a given element. It MUST return a list of objects which describes the available context menu items using the following algorithm for each menu item:

  • Let menuitem be a new JSON Object.

  • Set the property id on menuitem to a string which is unique for the current session.

  • Set the property menuItemTitle on menuitem to the text that is displayed in the UI.

  • Set the property icon on menuitem to the filename of the icon file or an empty string if none is displayed. If the icon is set because of the type of the context menu item (such as a radio button or checkbox), the icon property MUST be set to a string which is consistent for all icons of that type and status (e.g. checked), including across sessions.

  • Set the property parent on menuitem to the id of the item's parent or an empty string if the menuitem does not have a parent.

  • Set the property itemType on menuitem to a string value identifying the control type.

    String Value Description
    checkbox A checkbox element
    normal A standard menuItem element (text label)
    radio A radio element. Within a radio group, only one menuItem will have a value of true
    separator A horizontal line separator, typically used between groups of related items such as radio groups
  • Set the property itemChecked on menuitem to a boolean value indicating state of the item according to the following table. This applies only to items of itemType checkbox or radio. Within a radio group, only one menuItem will have a value of true.

    Boolean Value Description
    true Selected
    false Not selected
  • Return success with data menuitem

This list MUST contain all context menu items added by browser extensions and MUST NOT contain any other context menu items.

After this command has been run, the context menu MUST remain open until the next command that dismisses it (e.g. clicking, navigation) has been run.

WebElement elementId
The id of the element for which the context menu should be opened.

selectBrowserExtContextMenuItem()

HTTP Method Path Template Notes
POST /session/{sessionId}/element/{elementId}/browserext/contextMenuItem/{menuitemId}

This command causes a context menu item to be selected. This MUST have the same effect as a user clicking or tapping the item in the open context menu. If the menu item is a parent of other menu items, this command MAY open a submenu, but MUST NOT have any other effect.

This command MUST be executed even if there is no context menu open.

String menuitemId
The context menu item id, as returned by the getBrowserExtContextMenuItems() command.

If no context menu is currently open, a no such extension context menu item status code MUST be returned.

getBrowserExtPermissionPrompt()

HTTP Method Path Template Notes
GET /session/{sessionId}/browserext/permissionPrompt

Upon installation of a browser extension, a browser MAY notify the user of potential privacy-related capabilities of the extension. For example, if an extension's manifest.json requests the "tabs" or "webNavigation" permission, the browser MAY request user confirmation of these permissions. This command returns a JSON object that includes the names of permissions which require user confirmation and other information about the prompt. A similar prompt MAY also occur if an extension has been updated and the newer version requires additional permisisons. If there is no prompt at the time this API is called, the error "no such browser extension permission prompt" is returned.

  • Let permissionPrompt be a new JSON Object.
  • Set the property promptId to a string which is unique for each time a prompt is displayed.
  • Set the property promptMessageText to a string which represents the text shown to the user, localized to the default locale specified in manifest.json.
  • Set the property promptDefaultLocale to the default locale code specified in manifest.json. If locales are not used by the extension, the property SHOULD be omitted, but MAY return an empty string ("").
  • Set the property promptRequestingUrl to a string representing the relevant URL. Strings returned here are the same strings defined in the "permissions": [ ] section of manisfest.json. If a URL is not applicable to the prompt, the property SHOULD be omitted but MAY also return an empty string ("").
  • Set the property promptPermissions to an array of strings which correspond to requested permissions. Strings returned here are the same strings defined in the "permissions": [ ] section of manisfest.json. If permissions are not applicable to the prompt, the property SHOULD be omitted, but MAY include an empty array ([]) or an array of empty strings ([""]).
  • Set the property promptActions to an array of strings which correspond to possible actions the user could take. The actions allow and deny are required. Other optional values MAY be returned, but the behavior is not prescribed in this specification.
promptAction Required Description
allow Required Allows the extension to use or access the capabilities or sites
deny Required Denies extension's use of the requested capabilities or sites. The browser implementation of deny is not prescribed in this specification, and MAY result in the cancellation of the extension's installation.
dismiss Optional Some browsers MAY provide the user with an option to close a prompt without taking an accept or deny action. The browser implementation of dismiss is not prescribed in this specification, and MAY result in the cancellation of the extension's installation.
{custom} Optional Some browsers MAY provide additional options not prescribed in this table. For example, alwaysAllow, allowOnce or allowForThisSiteOnly may be presented in a permission prompt. The browser implementation for these custom actions is not prescribed in this specification.

takeBrowserExtPermissionPromptAction()

HTTP Method Path Template Notes
POST /session/{sessionId}/browserext/permissionPrompt/{promptId}/action/{promptAction}

Performs the action specified by promptAction. If there is no prompt at the time this API is called, or if the requested promptId is not available, the error "no such browser extension permission prompt" is returned. If the requested promptAction is not available, the error "no such browser extension permission prompt action" is returned.

Packaging

Overview

Browser extensions MAY be distributed and subsequently loaded as individual files or via a container, such as a *.zip archive. Regardless of the packaging format, these containers MUST contain the following:

Digital signatures

Browser vendors MAY require that extension packages include a digital signature. The signature MAY indicate the source of the extension, such as a distribution store or the extension's publisher. This aspect of packaging varies by browser, and browser implementers MAY enforce different requirements.

Acknowledgements

Many thanks to the members of the Browser Extension Community Group for their detailed feedback on this specification. Thanks to the members of the Browser Testing and Tools Working Group for their recommendations and feedback on WebDriver support.

Some sections are reproduced from MDN: