// Type definitions for non-npm package WebExtension Development in FireFox 70.0 // Project: https://developer.mozilla.org/en-US/Add-ons/WebExtensions // Definitions by: Jasmin Bom // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.9 // Generated using script at github.com/jsmnbom/definitelytyped-firefox-webext-browser interface WebExtEvent any> { addListener(cb: TCallback): void; removeListener(cb: TCallback): void; hasListener(cb: TCallback): boolean; } interface Window { browser: typeof browser; } /** Not allowed in: Content scripts, Devtools pages */ declare namespace browser._manifest { /* _manifest types */ type Permission = string | OptionalPermission | _Permission; type OptionalPermission = _OptionalPermission; /** Represents a WebExtension manifest.json file */ interface WebExtensionManifest { experiment_apis?: { [key: string]: experiments.ExperimentAPI }; /** A list of protocol handler definitions. */ protocol_handlers?: ProtocolHandler[]; default_locale?: string; minimum_chrome_version?: string; minimum_opera_version?: string; icons?: { [key: number]: ExtensionFileUrl; }; incognito?: _WebExtensionManifestIncognito; background?: { page: ExtensionURL; persistent?: PersistentBackgroundProperty; } | { scripts: ExtensionURL[]; persistent?: PersistentBackgroundProperty; }; options_ui?: { page: ExtensionURL; browser_style?: boolean; chrome_style?: boolean; open_in_tab?: boolean; }; content_scripts?: ContentScript[]; content_security_policy?: string; permissions?: PermissionOrOrigin[]; optional_permissions?: OptionalPermissionOrOrigin[]; web_accessible_resources?: string[]; developer?: { name?: string; url?: string; }; hidden?: boolean; theme_experiment?: ThemeExperiment; user_scripts?: { api_script?: ExtensionURL; }; browser_action?: { default_title?: string; default_icon?: IconPath; /** Specifies icons to use for dark and light themes */ theme_icons?: ThemeIcons[]; default_popup?: string; browser_style?: boolean; /** Defines the location the browserAction will appear by default. The default location is navbar. */ default_area?: _WebExtensionManifestBrowserActionDefaultArea; }; chrome_settings_overrides?: { homepage?: string; search_provider?: { name: string; keyword?: string; search_url: string; favicon_url?: string; suggest_url?: string; /** @deprecated Unsupported on Firefox at this time. */ instant_url?: string; /** @deprecated Unsupported on Firefox at this time. */ image_url?: string; /** GET parameters to the search_url as a query string. */ search_url_get_params?: string; /** POST parameters to the search_url as a query string. */ search_url_post_params?: string; /** GET parameters to the suggest_url as a query string. */ suggest_url_get_params?: string; /** POST parameters to the suggest_url as a query string. */ suggest_url_post_params?: string; /** @deprecated Unsupported on Firefox at this time. */ instant_url_post_params?: string; /** @deprecated Unsupported on Firefox at this time. */ image_url_post_params?: string; search_form?: string; /** @deprecated Unsupported on Firefox at this time. */ alternate_urls?: string[]; /** @deprecated Unsupported on Firefox. */ prepopulated_id?: number; /** Encoding of the search term. */ encoding?: string; /** Sets the default engine to a built-in engine only. */ is_default?: boolean; /** * A list of optional search url parameters. This allows the additon of search url parameters based on * how the search is performed in Firefox. */ params?: Array<{ /** A url parameter name */ name: string; /** The type of param can be either "purpose" or "pref". */ condition?: _WebExtensionManifestChromeSettingsOverridesSearchProviderParamsCondition; /** The preference to retreive the value from. */ pref?: string; /** The context that initiates a search, required if condition is "purpose". */ purpose?: _WebExtensionManifestChromeSettingsOverridesSearchProviderParamsPurpose; /** A url parameter value. */ value?: string; }>; }; }; commands?: { [key: string]: { suggested_key?: { default?: KeyName; mac?: KeyName; linux?: KeyName; windows?: KeyName; chromeos?: string; android?: string; ios?: string; /** @deprecated Unknown platform name */ additionalProperties?: string; }; description?: string; } }; devtools_page?: ExtensionURL; omnibox?: { keyword: string; }; page_action?: { default_title?: string; default_icon?: IconPath; default_popup?: string; browser_style?: boolean; show_matches?: MatchPattern[]; hide_matches?: MatchPatternRestricted[]; pinned?: boolean; }; sidebar_action?: { default_title?: string; default_icon?: IconPath; browser_style?: boolean; default_panel: string; /** Whether or not the sidebar is opened at install. Default is `true`. */ open_at_install?: boolean; }; chrome_url_overrides?: { newtab?: ExtensionURL; /** @deprecated Unsupported on Firefox at this time. */ bookmarks?: ExtensionURL; /** @deprecated Unsupported on Firefox at this time. */ history?: ExtensionURL; }; manifest_version: number; applications?: { gecko?: FirefoxSpecificProperties; }; browser_specific_settings?: { gecko?: FirefoxSpecificProperties; edge?: { [key: string]: any }; }; name: string; short_name?: string; description?: string; author?: string; version: string; homepage_url?: string; } /** Represents a protocol handler definition. */ interface ProtocolHandler { /** * A user-readable title string for the protocol handler. This will be displayed to the user in interface * objects as needed. */ name: string; /** * The protocol the site wishes to handle, specified as a string. For example, you can register to handle SMS * text message links by registering to handle the "sms" scheme. */ protocol: string | _ProtocolHandlerProtocol; /** * The URL of the handler, as a string. This string should include "%s" as a placeholder which will be replaced * with the escaped URL of the document to be handled. This URL might be a true URL, or it could be a phone * number, email address, or so forth. */ uriTemplate: ExtensionURL | HttpURL; } /** Common properties for all manifest.json files */ interface ManifestBase { manifest_version: number; applications?: { gecko?: FirefoxSpecificProperties; }; browser_specific_settings?: { gecko?: FirefoxSpecificProperties; edge?: { [key: string]: any }; }; name: string; short_name?: string; description?: string; author?: string; version: string; homepage_url?: string; } /** Represents a WebExtension language pack manifest.json file */ interface WebExtensionLangpackManifest { homepage_url?: string; langpack_id: string; languages: { [key: string]: { chrome_resources: { [key: string]: ExtensionURL | { [key: string]: ExtensionURL; }; }; version: string; }; }; sources?: { [key: string]: { base_path: ExtensionURL; paths?: string[]; }; }; manifest_version: number; applications?: { gecko?: FirefoxSpecificProperties; }; browser_specific_settings?: { gecko?: FirefoxSpecificProperties; edge?: { [key: string]: any }; }; name: string; short_name?: string; description?: string; author?: string; version: string; } /** Represents a WebExtension dictionary manifest.json file */ interface WebExtensionDictionaryManifest { homepage_url?: string; dictionaries: { [key: string]: string; }; manifest_version: number; applications?: { gecko?: FirefoxSpecificProperties; }; browser_specific_settings?: { gecko?: FirefoxSpecificProperties; edge?: { [key: string]: any }; }; name: string; short_name?: string; description?: string; author?: string; version: string; } interface ThemeIcons { /** A light icon to use for dark themes */ light: ExtensionURL; /** The dark icon to use for light themes */ dark: ExtensionURL; /** The size of the icons */ size: number; } type OptionalPermissionOrOrigin = OptionalPermission | MatchPattern; type PermissionOrOrigin = Permission | MatchPattern; type HttpURL = string; type ExtensionURL = string; type ExtensionFileUrl = string; type ImageDataOrExtensionURL = string; type ExtensionID = string; interface FirefoxSpecificProperties { id?: ExtensionID; update_url?: string; strict_min_version?: string; strict_max_version?: string; } type MatchPattern = MatchPatternRestricted | MatchPatternUnestricted | _MatchPattern; /** Same as MatchPattern above, but excludes */ type MatchPatternRestricted = string; /** * Mostly unrestricted match patterns for privileged add-ons. This should technically be rejected for unprivileged * add-ons, but, reasons. The MatchPattern class will still refuse privileged schemes for those extensions. */ type MatchPatternUnestricted = string; /** * Details of the script or CSS to inject. Either the code or the file property must be set, but both may not be * set at the same time. Based on InjectDetails, but using underscore rather than camel case naming conventions. */ interface ContentScript { matches: MatchPattern[]; exclude_matches?: MatchPattern[]; include_globs?: string[]; exclude_globs?: string[]; /** The list of CSS files to inject */ css?: ExtensionURL[]; /** The list of JS files to inject */ js?: ExtensionURL[]; /** * If allFrames is `true`, implies that the JavaScript or CSS should be injected into all frames of current * page. By default, it's `false` and is only injected into the top frame. */ all_frames?: boolean; /** * If matchAboutBlank is true, then the code is also injected in about:blank and about:srcdoc frames if your * extension has access to its parent document. Code cannot be inserted in top-level about:-frames. By default * it is `false`. */ match_about_blank?: boolean; /** The soonest that the JavaScript or CSS will be injected into the tab. Defaults to "document_idle". */ run_at?: extensionTypes.RunAt; } type IconPath = { [key: number]: ExtensionFileUrl; } | ExtensionFileUrl; type IconImageData = { [key: number]: ImageData; } | ImageData; type ImageData = any; /** @deprecated An unexpected property was found in the WebExtension manifest. */ type UnrecognizedProperty = any; /** @deprecated Event pages are not currently supported. This will run as a persistent background page. */ type PersistentBackgroundProperty = boolean; /** Represents a native manifest file */ type NativeManifest = { name: string; description: string; path: string; type: "pkcs11" | "stdio"; allowed_extensions: ExtensionID[]; } | { name: ExtensionID; description: string; data: { [key: string]: any }; type: "storage"; }; type ThemeColor = string | [number, number, number] | [number, number, number, number]; interface ThemeExperiment { stylesheet?: ExtensionURL; images?: { [key: string]: string }; colors?: { [key: string]: string }; properties?: { [key: string]: string }; } interface ThemeType { images?: { additional_backgrounds?: ImageDataOrExtensionURL[]; /** * @deprecated Unsupported images property, use 'theme.images.theme_frame', this alias is ignored in * Firefox >= 70. */ headerURL?: ImageDataOrExtensionURL; theme_frame?: ImageDataOrExtensionURL; }; colors?: { tab_selected?: ThemeColor; /** * @deprecated Unsupported colors property, use 'theme.colors.frame', this alias is ignored in Firefox >= * 70. */ accentcolor?: ThemeColor; frame?: ThemeColor; frame_inactive?: ThemeColor; /** * @deprecated Unsupported color property, use 'theme.colors.tab_background_text', this alias is ignored in * Firefox >= 70. */ textcolor?: ThemeColor; tab_background_text?: ThemeColor; tab_background_separator?: ThemeColor; tab_loading?: ThemeColor; tab_text?: ThemeColor; tab_line?: ThemeColor; toolbar?: ThemeColor; /** This color property is an alias of 'bookmark_text'. */ toolbar_text?: ThemeColor; bookmark_text?: ThemeColor; toolbar_field?: ThemeColor; toolbar_field_text?: ThemeColor; toolbar_field_border?: ThemeColor; toolbar_field_separator?: ThemeColor; toolbar_top_separator?: ThemeColor; toolbar_bottom_separator?: ThemeColor; toolbar_vertical_separator?: ThemeColor; icons?: ThemeColor; icons_attention?: ThemeColor; button_background_hover?: ThemeColor; button_background_active?: ThemeColor; popup?: ThemeColor; popup_text?: ThemeColor; popup_border?: ThemeColor; toolbar_field_focus?: ThemeColor; toolbar_field_text_focus?: ThemeColor; toolbar_field_border_focus?: ThemeColor; popup_highlight?: ThemeColor; popup_highlight_text?: ThemeColor; ntp_background?: ThemeColor; ntp_text?: ThemeColor; sidebar?: ThemeColor; sidebar_border?: ThemeColor; sidebar_text?: ThemeColor; sidebar_highlight?: ThemeColor; sidebar_highlight_text?: ThemeColor; toolbar_field_highlight?: ThemeColor; toolbar_field_highlight_text?: ThemeColor; }; properties?: { additional_backgrounds_alignment?: _ThemeTypeAdditionalBackgroundsAlignment[]; additional_backgrounds_tiling?: _ThemeTypeAdditionalBackgroundsTiling[]; }; } /** Contents of manifest.json for a static theme */ interface ThemeManifest { theme: ThemeType; dark_theme?: ThemeType; default_locale?: string; theme_experiment?: ThemeExperiment; icons?: { [key: number]: string; }; } type KeyName = string; type _Permission = "activityLog" | "captivePortal" | "contextualIdentities" | "dns" | "geckoProfiler" | "identity" | "management" | "alarms" | "mozillaAddons" | "storage" | "unlimitedStorage" | "networkStatus" | "privacy" | "proxy" | "nativeMessaging" | "telemetry" | "theme" | "browsingData" | "devtools" | "menus" | "contextMenus" | "normandyAddonStudy" | "pkcs11" | "sessions" | "urlbar"; type _OptionalPermission = "browserSettings" | "cookies" | "downloads" | "downloads.open" | "clipboardRead" | "clipboardWrite" | "geolocation" | "idle" | "notifications" | "webNavigation" | "webRequest" | "webRequestBlocking" | "bookmarks" | "find" | "history" | "menus.overrideContext" | "search" | "activeTab" | "tabs" | "tabHide" | "topSites"; type _WebExtensionManifestIncognito = "not_allowed" | "spanning"; /** Defines the location the browserAction will appear by default. The default location is navbar. */ type _WebExtensionManifestBrowserActionDefaultArea = "navbar" | "menupanel" | "tabstrip" | "personaltoolbar"; /** The type of param can be either "purpose" or "pref". */ type _WebExtensionManifestChromeSettingsOverridesSearchProviderParamsCondition = "purpose" | "pref"; /** The context that initiates a search, required if condition is "purpose". */ type _WebExtensionManifestChromeSettingsOverridesSearchProviderParamsPurpose = "contextmenu" | "searchbar" | "homepage" | "keyword" | "newtab"; type _ProtocolHandlerProtocol = "bitcoin" | "dat" | "dweb" | "geo" | "gopher" | "im" | "ipfs" | "ipns" | "irc" | "ircs" | "magnet" | "mailto" | "mms" | "news" | "nntp" | "sip" | "sms" | "smsto" | "ssb" | "ssh" | "tel" | "urn" | "webcal" | "wtai" | "xmpp"; type _MatchPattern = ""; type _ThemeTypeAdditionalBackgroundsAlignment = "bottom" | "center" | "left" | "right" | "top" | "center bottom" | "center center" | "center top" | "left bottom" | "left center" | "left top" | "right bottom" | "right center" | "right top"; type _ThemeTypeAdditionalBackgroundsTiling = "no-repeat" | "repeat" | "repeat-x" | "repeat-y"; } /** * Monitor extension activity * * Permissions: `activityLog` * * Not allowed in: Content scripts, Devtools pages */ declare namespace browser.activityLog { /** * The type of log entry. api_call is a function call made by the extension and api_event is an event callback to * the extension. content_script is logged when a content script is injected. */ type _UndefinedType = "api_call" | "api_event" | "content_script" | "user_script"; /** The type of view where the activity occurred. Content scripts will not have a viewType. */ type _UndefinedViewType = "background" | "popup" | "sidebar" | "tab" | "devtools_page" | "devtools_panel"; interface _ActivityLogOnExtensionActivityEvent void> { addListener(cb: TCallback, id: string): void; removeListener(cb: TCallback): void; hasListener(cb: TCallback): boolean; } /* activityLog events */ /** Receives an activityItem for each logging event. */ const onExtensionActivity: _ActivityLogOnExtensionActivityEvent; } /** * Permissions: `alarms` * * Not allowed in: Content scripts, Devtools pages */ declare namespace browser.alarms { /* alarms types */ interface Alarm { /** Name of this alarm. */ name: string; /** Time when the alarm is scheduled to fire, in milliseconds past the epoch. */ scheduledTime: number; /** When present, signals that the alarm triggers periodically after so many minutes. */ periodInMinutes?: number; } /* alarms functions */ /** * Creates an alarm. After the delay is expired, the onAlarm event is fired. If there is another alarm with the * same name (or no name if none is specified), it will be cancelled and replaced by this alarm. * @param alarmInfo Details about the alarm. The alarm first fires either at 'when' milliseconds past the epoch (if * 'when' is provided), after 'delayInMinutes' minutes from the current time (if 'delayInMinutes' is provided * instead), or after 'periodInMinutes' minutes from the current time (if only 'periodInMinutes' is provided). * Users should never provide both 'when' and 'delayInMinutes'. If 'periodInMinutes' is provided, then the * alarm recurs repeatedly after that many minutes. */ function create(alarmInfo: { /** Time when the alarm is scheduled to first fire, in milliseconds past the epoch. */ when?: number; /** Number of minutes from the current time after which the alarm should first fire. */ delayInMinutes?: number; /** Number of minutes after which the alarm should recur repeatedly. */ periodInMinutes?: number; }): void; /** * Creates an alarm. After the delay is expired, the onAlarm event is fired. If there is another alarm with the * same name (or no name if none is specified), it will be cancelled and replaced by this alarm. * @param name Optional name to identify this alarm. Defaults to the empty string. * @param alarmInfo Details about the alarm. The alarm first fires either at 'when' milliseconds past the epoch (if * 'when' is provided), after 'delayInMinutes' minutes from the current time (if 'delayInMinutes' is provided * instead), or after 'periodInMinutes' minutes from the current time (if only 'periodInMinutes' is provided). * Users should never provide both 'when' and 'delayInMinutes'. If 'periodInMinutes' is provided, then the * alarm recurs repeatedly after that many minutes. */ function create(name: string, alarmInfo: { /** Time when the alarm is scheduled to first fire, in milliseconds past the epoch. */ when?: number; /** Number of minutes from the current time after which the alarm should first fire. */ delayInMinutes?: number; /** Number of minutes after which the alarm should recur repeatedly. */ periodInMinutes?: number; }): void; /** * Retrieves details about the specified alarm. * @param [name] The name of the alarm to get. Defaults to the empty string. */ function get(name?: string): Promise; /** Gets an array of all the alarms. */ function getAll(): Promise; /** * Clears the alarm with the given name. * @param [name] The name of the alarm to clear. Defaults to the empty string. */ function clear(name?: string): Promise; /** Clears all alarms. */ function clearAll(): Promise; /* alarms events */ /** * Fired when an alarm has expired. Useful for transient background pages. * @param name The alarm that has expired. */ const onAlarm: WebExtEvent<(name: Alarm) => void>; } /** * Use the `browser.browserSettings` API to control global settings of the browser. * * Permissions: `browserSettings` * * Not allowed in: Content scripts, Devtools pages */ declare namespace browser.browserSettings { /* browserSettings types */ /** How images should be animated in the browser. */ type ImageAnimationBehavior = "normal" | "none" | "once"; /** After which mouse event context menus should popup. */ type ContextMenuMouseEvent = "mouseup" | "mousedown"; /* browserSettings properties */ /** Allows or disallows pop-up windows from opening in response to user events. */ const allowPopupsForUserEvents: types.Setting; /** Enables or disables the browser cache. */ const cacheEnabled: types.Setting; /** This boolean setting controls whether the selected tab can be closed with a double click. */ const closeTabsByDoubleClick: types.Setting; /** * Controls after which mouse event context menus popup. This setting's value is of type ContextMenuMouseEvent, * which has possible values of `mouseup` and `mousedown`. */ const contextMenuShowEvent: types.Setting; /** Returns the value of the overridden home page. Read-only. */ const homepageOverride: types.Setting; /** * Controls the behaviour of image animation in the browser. This setting's value is of type * ImageAnimationBehavior, defaulting to `normal`. */ const imageAnimationBehavior: types.Setting; /** Returns the value of the overridden new tab page. Read-only. */ const newTabPageOverride: types.Setting; /** * Controls where new tabs are opened. `afterCurrent` will open all new tabs next to the current tab, * `relatedAfterCurrent` will open only related tabs next to the current tab, and `atEnd` will open all tabs at the * end of the tab strip. The default is `relatedAfterCurrent`. */ const newTabPosition: types.Setting; /** This boolean setting controls whether bookmarks are opened in the current tab or in a new tab. */ const openBookmarksInNewTabs: types.Setting; /** This boolean setting controls whether search results are opened in the current tab or in a new tab. */ const openSearchResultsInNewTabs: types.Setting; /** This boolean setting controls whether urlbar results are opened in the current tab or in a new tab. */ const openUrlbarResultsInNewTabs: types.Setting; /** Disables webAPI notifications. */ const webNotificationsDisabled: types.Setting; /** This setting controls whether the user-chosen colors override the page's colors. */ const overrideDocumentColors: types.Setting; /** This setting controls whether the document's fonts are used. */ const useDocumentFonts: types.Setting; } /** * This API provides the ability detect the captive portal state of the users connection. * * Permissions: `captivePortal` * * Not allowed in: Content scripts, Devtools pages */ declare namespace browser.captivePortal { /** The current captive portal state. */ type _UndefinedState = "unknown" | "not_captive" | "unlocked_portal" | "locked_portal"; type _Status = "captive" | "clear"; /* captivePortal functions */ /** * Returns the current portal state, one of `unknown`, `not_captive`, `unlocked_portal`, `locked_portal`. */ function getState(): Promise<_UndefinedState>; /** Returns the time difference between NOW and the last time a request was completed in milliseconds. */ function getLastChecked(): Promise; /* captivePortal events */ /** Fired when the captive portal state changes. */ const onStateChanged: WebExtEvent<(details: { /** The current captive portal state. */ state: _UndefinedState; }) => void>; /** * This notification will be emitted when the captive portal service has determined that we can connect to the * internet. The service will pass either `captive` if there is an unlocked captive portal present, or `clear` if * no captive portal was detected. */ const onConnectivityAvailable: WebExtEvent<(status: _Status) => void>; } /** * Offers the ability to write to the clipboard. Reading is not supported because the clipboard can already be read * through the standard web platform APIs. * * Permissions: `clipboardWrite` * * Not allowed in: Content scripts, Devtools pages */ declare namespace browser.clipboard { type ArrayBuffer = any; /** The type of imageData. */ type _SetImageData = "jpeg" | "png"; /* clipboard functions */ /** * Copy an image to the clipboard. The image is re-encoded before it is written to the clipboard. If the image is * invalid, the clipboard is not modified. * @param imageData The image data to be copied. * @param imageType The type of imageData. */ function setImageData(imageData: ArrayBuffer, imageType: _SetImageData): Promise; } /** Not allowed in: Content scripts, Devtools pages */ declare namespace browser.contentScripts { /* contentScripts types */ /** Details of a content script registered programmatically */ interface RegisteredContentScriptOptions { matches: _manifest.MatchPattern[]; excludeMatches?: _manifest.MatchPattern[]; includeGlobs?: string[]; excludeGlobs?: string[]; /** The list of CSS files to inject */ css?: extensionTypes.ExtensionFileOrCode[]; /** The list of JS files to inject */ js?: extensionTypes.ExtensionFileOrCode[]; /** * If allFrames is `true`, implies that the JavaScript or CSS should be injected into all frames of current * page. By default, it's `false` and is only injected into the top frame. */ allFrames?: boolean; /** * If matchAboutBlank is true, then the code is also injected in about:blank and about:srcdoc frames if your * extension has access to its parent document. Code cannot be inserted in top-level about:-frames. By default * it is `false`. */ matchAboutBlank?: boolean; /** The soonest that the JavaScript or CSS will be injected into the tab. Defaults to "document_idle". */ runAt?: extensionTypes.RunAt; } /** An object that represents a content script registered programmatically */ interface RegisteredContentScript { /** Unregister a content script registered programmatically */ unregister(): Promise; } /* contentScripts functions */ /** Register a content script programmatically */ function register(contentScriptOptions: RegisteredContentScriptOptions): Promise; } /** * Use the `browser.contextualIdentities` API to query and modify contextual identity, also called as containers. * * Permissions: `contextualIdentities` * * Not allowed in: Content scripts, Devtools pages */ declare namespace browser.contextualIdentities { /* contextualIdentities types */ /** Represents information about a contextual identity. */ interface ContextualIdentity { /** The name of the contextual identity. */ name: string; /** The icon name of the contextual identity. */ icon: string; /** The icon url of the contextual identity. */ iconUrl: string; /** The color name of the contextual identity. */ color: string; /** The color hash of the contextual identity. */ colorCode: string; /** The cookie store ID of the contextual identity. */ cookieStoreId: string; } /* contextualIdentities functions */ /** * Retrieves information about a single contextual identity. * @param cookieStoreId The ID of the contextual identity cookie store. */ function get(cookieStoreId: string): Promise; /** * Retrieves all contextual identities * @param details Information to filter the contextual identities being retrieved. */ function query(details: { /** Filters the contextual identity by name. */ name?: string; }): Promise; /** * Creates a contextual identity with the given data. * @param details Details about the contextual identity being created. */ function create(details: { /** The name of the contextual identity. */ name: string; /** The color of the contextual identity. */ color: string; /** The icon of the contextual identity. */ icon: string; }): Promise; /** * Updates a contextual identity with the given data. * @param cookieStoreId The ID of the contextual identity cookie store. * @param details Details about the contextual identity being created. */ function update(cookieStoreId: string, details: { /** The name of the contextual identity. */ name?: string; /** The color of the contextual identity. */ color?: string; /** The icon of the contextual identity. */ icon?: string; }): Promise; /** * Deletes a contetual identity by its cookie Store ID. * @param cookieStoreId The ID of the contextual identity cookie store. */ function remove(cookieStoreId: string): Promise; /* contextualIdentities events */ /** Fired when a container is updated. */ const onUpdated: WebExtEvent<(changeInfo: { /** Contextual identity that has been updated */ contextualIdentity: ContextualIdentity; }) => void>; /** Fired when a new container is created. */ const onCreated: WebExtEvent<(changeInfo: { /** Contextual identity that has been created */ contextualIdentity: ContextualIdentity; }) => void>; /** Fired when a container is removed. */ const onRemoved: WebExtEvent<(changeInfo: { /** Contextual identity that has been removed */ contextualIdentity: ContextualIdentity; }) => void>; } /** * Use the `browser.cookies` API to query and modify cookies, and to be notified when they change. * * Permissions: `cookies` * * Not allowed in: Content scripts, Devtools pages */ declare namespace browser.cookies { /* cookies types */ /** * A cookie's 'SameSite' state (https://tools.ietf.org/html/draft-west-first-party-cookies). 'no_restriction' * corresponds to a cookie set without a 'SameSite' attribute, 'lax' to 'SameSite=Lax', and 'strict' to * 'SameSite=Strict'. */ type SameSiteStatus = "no_restriction" | "lax" | "strict"; /** Represents information about an HTTP cookie. */ interface Cookie { /** The name of the cookie. */ name: string; /** The value of the cookie. */ value: string; /** The domain of the cookie (e.g. "www.google.com", "example.com"). */ domain: string; /** * True if the cookie is a host-only cookie (i.e. a request's host must exactly match the domain of the cookie). */ hostOnly: boolean; /** The path of the cookie. */ path: string; /** * True if the cookie is marked as Secure (i.e. its scope is limited to secure channels, typically HTTPS). */ secure: boolean; /** True if the cookie is marked as HttpOnly (i.e. the cookie is inaccessible to client-side scripts). */ httpOnly: boolean; /** The cookie's same-site status (i.e. whether the cookie is sent with cross-site requests). */ sameSite: SameSiteStatus; /** True if the cookie is a session cookie, as opposed to a persistent cookie with an expiration date. */ session: boolean; /** * The expiration date of the cookie as the number of seconds since the UNIX epoch. Not provided for session * cookies. */ expirationDate?: number; /** The ID of the cookie store containing this cookie, as provided in getAllCookieStores(). */ storeId: string; /** The first-party domain of the cookie. */ firstPartyDomain: string; } /** * Represents a cookie store in the browser. An incognito mode window, for instance, uses a separate cookie store * from a non-incognito window. */ interface CookieStore { /** The unique identifier for the cookie store. */ id: string; /** Identifiers of all the browser tabs that share this cookie store. */ tabIds: number[]; /** Indicates if this is an incognito cookie store */ incognito: boolean; } /** * The underlying reason behind the cookie's change. If a cookie was inserted, or removed via an explicit call to * `cookies.remove`, "cause" will be "explicit". If a cookie was automatically removed due to expiry, "cause" will * be "expired". If a cookie was removed due to being overwritten with an already-expired expiration date, "cause" * will be set to "expired_overwrite". If a cookie was automatically removed due to garbage collection, "cause" * will be "evicted". If a cookie was automatically removed due to a "set" call that overwrote it, "cause" will be * "overwrite". Plan your response accordingly. */ type OnChangedCause = "evicted" | "expired" | "explicit" | "expired_overwrite" | "overwrite"; /* cookies functions */ /** * Retrieves information about a single cookie. If more than one cookie of the same name exists for the given URL, * the one with the longest path will be returned. For cookies with the same path length, the cookie with the * earliest creation time will be returned. * @param details Details to identify the cookie being retrieved. */ function get(details: { /** * The URL with which the cookie to retrieve is associated. This argument may be a full URL, in which case any * data following the URL path (e.g. the query string) is simply ignored. If host permissions for this URL are * not specified in the manifest file, the API call will fail. */ url: string; /** The name of the cookie to retrieve. */ name: string; /** * The ID of the cookie store in which to look for the cookie. By default, the current execution context's * cookie store will be used. */ storeId?: string; /** * The first-party domain which the cookie to retrieve is associated. This attribute is required if First-Party * Isolation is enabled. */ firstPartyDomain?: string; }): Promise; /** * Retrieves all cookies from a single cookie store that match the given information. The cookies returned will be * sorted, with those with the longest path first. If multiple cookies have the same path length, those with the * earliest creation time will be first. * @param details Information to filter the cookies being retrieved. */ function getAll(details: { /** Restricts the retrieved cookies to those that would match the given URL. */ url?: string; /** Filters the cookies by name. */ name?: string; /** Restricts the retrieved cookies to those whose domains match or are subdomains of this one. */ domain?: string; /** Restricts the retrieved cookies to those whose path exactly matches this string. */ path?: string; /** Filters the cookies by their Secure property. */ secure?: boolean; /** Filters out session vs. persistent cookies. */ session?: boolean; /** * The cookie store to retrieve cookies from. If omitted, the current execution context's cookie store will be * used. */ storeId?: string; /** * Restricts the retrieved cookies to those whose first-party domains match this one. This attribute is * required if First-Party Isolation is enabled. To not filter by a specific first-party domain, use `null` or * `undefined`. */ firstPartyDomain?: string; }): Promise; /** * Sets a cookie with the given cookie data; may overwrite equivalent cookies if they exist. * @param details Details about the cookie being set. */ function set(details: { /** * The request-URI to associate with the setting of the cookie. This value can affect the default domain and * path values of the created cookie. If host permissions for this URL are not specified in the manifest file, * the API call will fail. */ url: string; /** The name of the cookie. Empty by default if omitted. */ name?: string; /** The value of the cookie. Empty by default if omitted. */ value?: string; /** The domain of the cookie. If omitted, the cookie becomes a host-only cookie. */ domain?: string; /** The path of the cookie. Defaults to the path portion of the url parameter. */ path?: string; /** Whether the cookie should be marked as Secure. Defaults to false. */ secure?: boolean; /** Whether the cookie should be marked as HttpOnly. Defaults to false. */ httpOnly?: boolean; /** The cookie's same-site status. */ sameSite?: SameSiteStatus; /** * The expiration date of the cookie as the number of seconds since the UNIX epoch. If omitted, the cookie * becomes a session cookie. */ expirationDate?: number; /** * The ID of the cookie store in which to set the cookie. By default, the cookie is set in the current * execution context's cookie store. */ storeId?: string; /** * The first-party domain of the cookie. This attribute is required if First-Party Isolation is enabled. */ firstPartyDomain?: string; }): Promise; /** * Deletes a cookie by name. * @param details Information to identify the cookie to remove. */ function remove(details: { /** * The URL associated with the cookie. If host permissions for this URL are not specified in the manifest file, * the API call will fail. */ url: string; /** The name of the cookie to remove. */ name: string; /** * The ID of the cookie store to look in for the cookie. If unspecified, the cookie is looked for by default in * the current execution context's cookie store. */ storeId?: string; /** * The first-party domain associated with the cookie. This attribute is required if First-Party Isolation is * enabled. */ firstPartyDomain?: string; }): Promise<{ /** The URL associated with the cookie that's been removed. */ url: string; /** The name of the cookie that's been removed. */ name: string; /** The ID of the cookie store from which the cookie was removed. */ storeId: string; /** The first-party domain associated with the cookie that's been removed. */ firstPartyDomain: string; }>; /** Lists all existing cookie stores. */ function getAllCookieStores(): Promise; /* cookies events */ /** * Fired when a cookie is set or removed. As a special case, note that updating a cookie's properties is * implemented as a two step process: the cookie to be updated is first removed entirely, generating a notification * with "cause" of "overwrite" . Afterwards, a new cookie is written with the updated values, generating a second * notification with "cause" "explicit". */ const onChanged: WebExtEvent<(changeInfo: { /** True if a cookie was removed. */ removed: boolean; /** Information about the cookie that was set or removed. */ cookie: Cookie; /** The underlying reason behind the cookie's change. */ cause: OnChangedCause; }) => void>; } /** * Asynchronous DNS API * * Permissions: `dns` * * Not allowed in: Content scripts, Devtools pages */ declare namespace browser.dns { /* dns types */ /** An object encapsulating a DNS Record. */ interface DNSRecord { /** * The canonical hostname for this record. this value is empty if the record was not fetched with the * 'canonical_name' flag. */ canonicalName?: string; /** Record retreived with TRR. */ isTRR: string; addresses: string[]; } type ResolveFlags = _ResolveFlags[]; type _ResolveFlags = "allow_name_collisions" | "bypass_cache" | "canonical_name" | "disable_ipv4" | "disable_ipv6" | "disable_trr" | "offline" | "priority_low" | "priority_medium" | "speculate"; /* dns functions */ /** Resolves a hostname to a DNS record. */ function resolve(hostname: string, flags?: ResolveFlags): Promise; } /** * Permissions: `downloads` * * Not allowed in: Content scripts, Devtools pages */ declare namespace browser.downloads { /* downloads types */ type FilenameConflictAction = "uniquify" | "overwrite" | "prompt"; type InterruptReason = "FILE_FAILED" | "FILE_ACCESS_DENIED" | "FILE_NO_SPACE" | "FILE_NAME_TOO_LONG" | "FILE_TOO_LARGE" | "FILE_VIRUS_INFECTED" | "FILE_TRANSIENT_ERROR" | "FILE_BLOCKED" | "FILE_SECURITY_CHECK_FAILED" | "FILE_TOO_SHORT" | "NETWORK_FAILED" | "NETWORK_TIMEOUT" | "NETWORK_DISCONNECTED" | "NETWORK_SERVER_DOWN" | "NETWORK_INVALID_REQUEST" | "SERVER_FAILED" | "SERVER_NO_RANGE" | "SERVER_BAD_CONTENT" | "SERVER_UNAUTHORIZED" | "SERVER_CERT_PROBLEM" | "SERVER_FORBIDDEN" | "USER_CANCELED" | "USER_SHUTDOWN" | "CRASH"; /** * *file*: * The download's filename is suspicious. * *url*: * The download's URL is known to be malicious. * *content*: * The downloaded file is known to be malicious. * *uncommon*: * The download's URL is not commonly downloaded and could be dangerous. * *safe*: * The download presents no known danger to the user's computer. * * These string constants will never change, however the set of DangerTypes may change. */ type DangerType = "file" | "url" | "content" | "uncommon" | "host" | "unwanted" | "safe" | "accepted"; /** * *in_progress*: * The download is currently receiving data from the server. * *interrupted*: * An error broke the connection with the file host. * *complete*: * The download completed successfully. * * These string constants will never change, however the set of States may change. */ type State = "in_progress" | "interrupted" | "complete"; interface DownloadItem { /** An identifier that is persistent across browser sessions. */ id: number; /** Absolute URL. */ url: string; referrer?: string; /** Absolute local path. */ filename: string; /** False if this download is recorded in the history, true if it is not recorded. */ incognito: boolean; /** Indication of whether this download is thought to be safe or known to be suspicious. */ danger: DangerType; /** The file's MIME type. */ mime?: string; /** Number of milliseconds between the unix epoch and when this download began. */ startTime: string; /** Number of milliseconds between the unix epoch and when this download ended. */ endTime?: string; estimatedEndTime?: string; /** Indicates whether the download is progressing, interrupted, or complete. */ state: State; /** True if the download has stopped reading data from the host, but kept the connection open. */ paused: boolean; canResume: boolean; /** Number indicating why a download was interrupted. */ error?: InterruptReason; /** Number of bytes received so far from the host, without considering file compression. */ bytesReceived: number; /** Number of bytes in the whole file, without considering file compression, or -1 if unknown. */ totalBytes: number; /** Number of bytes in the whole file post-decompression, or -1 if unknown. */ fileSize: number; exists: boolean; byExtensionId?: string; byExtensionName?: string; } interface StringDelta { current?: string; previous?: string; } interface DoubleDelta { current?: number; previous?: number; } interface BooleanDelta { current?: boolean; previous?: boolean; } /** * A time specified as a Date object, a number or string representing milliseconds since the epoch, or an ISO 8601 * string */ type DownloadTime = string | extensionTypes.Date; /** * Parameters that combine to specify a predicate that can be used to select a set of downloads. Used for example * in search() and erase() */ interface DownloadQuery { /** * This array of search terms limits results to DownloadItems whose `filename` or `url` contain all of the * search terms that do not begin with a dash '-' and none of the search terms that do begin with a dash. */ query?: string[]; /** Limits results to downloads that started before the given ms since the epoch. */ startedBefore?: DownloadTime; /** Limits results to downloads that started after the given ms since the epoch. */ startedAfter?: DownloadTime; /** Limits results to downloads that ended before the given ms since the epoch. */ endedBefore?: DownloadTime; /** Limits results to downloads that ended after the given ms since the epoch. */ endedAfter?: DownloadTime; /** Limits results to downloads whose totalBytes is greater than the given integer. */ totalBytesGreater?: number; /** Limits results to downloads whose totalBytes is less than the given integer. */ totalBytesLess?: number; /** Limits results to DownloadItems whose `filename` matches the given regular expression. */ filenameRegex?: string; /** Limits results to DownloadItems whose `url` matches the given regular expression. */ urlRegex?: string; /** * Setting this integer limits the number of results. Otherwise, all matching DownloadItems will be returned. */ limit?: number; /** * Setting elements of this array to DownloadItem properties in order to sort the search results. For example, * setting `orderBy='startTime'` sorts the DownloadItems by their start time in ascending order. To specify * descending order, prefix `orderBy` with a hyphen: '-startTime'. */ orderBy?: string[]; id?: number; /** Absolute URL. */ url?: string; /** Absolute local path. */ filename?: string; /** Indication of whether this download is thought to be safe or known to be suspicious. */ danger?: DangerType; /** The file's MIME type. */ mime?: string; startTime?: string; endTime?: string; /** Indicates whether the download is progressing, interrupted, or complete. */ state?: State; /** True if the download has stopped reading data from the host, but kept the connection open. */ paused?: boolean; /** Why a download was interrupted. */ error?: InterruptReason; /** Number of bytes received so far from the host, without considering file compression. */ bytesReceived?: number; /** Number of bytes in the whole file, without considering file compression, or -1 if unknown. */ totalBytes?: number; /** Number of bytes in the whole file post-decompression, or -1 if unknown. */ fileSize?: number; exists?: boolean; } /** The HTTP method to use if the URL uses the HTTP[S] protocol. */ type _DownloadMethod = "GET" | "POST"; /* downloads functions */ /** * Download a URL. If the URL uses the HTTP[S] protocol, then the request will include all cookies currently set * for its hostname. If both `filename` and `saveAs` are specified, then the Save As dialog will be displayed, * pre-populated with the specified `filename`. If the download started successfully, `callback` will be called * with the new DownloadItem's `downloadId`. If there was an error starting the download, then `callback` will be * called with `downloadId=undefined` and browser.extension.lastError will contain a descriptive string. The error * strings are not guaranteed to remain backwards compatible between releases. You must not parse it. * @param options What to download and how. */ function download(options: { /** The URL to download. */ url: string; /** A file path relative to the Downloads directory to contain the downloaded file. */ filename?: string; /** Whether to associate the download with a private browsing session. */ incognito?: boolean; conflictAction?: FilenameConflictAction; /** * Use a file-chooser to allow the user to select a filename. If the option is not specified, the file chooser * will be shown only if the Firefox "Always ask you where to save files" option is enabled (i.e. the pref * `browser.download.useDownloadDir` is set to `false`). */ saveAs?: boolean; /** The HTTP method to use if the URL uses the HTTP[S] protocol. */ method?: _DownloadMethod; /** * Extra HTTP headers to send with the request if the URL uses the HTTP[s] protocol. Each header is represented * as a dictionary containing the keys `name` and either `value` or `binaryValue`, restricted to those allowed * by XMLHttpRequest. */ headers?: Array<{ /** Name of the HTTP header. */ name: string; /** Value of the HTTP header. */ value: string; }>; /** Post body. */ body?: string; }): Promise; /** * Find DownloadItems. Set `query` to the empty object to get all DownloadItems. To get a specific DownloadItem, * set only the `id` field. */ function search(query: DownloadQuery): Promise; /** * Pause the download. If the request was successful the download is in a paused state. Otherwise * browser.extension.lastError contains an error message. The request will fail if the download is not active. * @param downloadId The id of the download to pause. */ function pause(downloadId: number): Promise; /** * Resume a paused download. If the request was successful the download is in progress and unpaused. Otherwise * browser.extension.lastError contains an error message. The request will fail if the download is not active. * @param downloadId The id of the download to resume. */ function resume(downloadId: number): Promise; /** * Cancel a download. When `callback` is run, the download is cancelled, completed, interrupted or doesn't exist * anymore. * @param downloadId The id of the download to cancel. */ function cancel(downloadId: number): Promise; /** * Retrieve an icon for the specified download. For new downloads, file icons are available after the onCreated * event has been received. The image returned by this function while a download is in progress may be different * from the image returned after the download is complete. Icon retrieval is done by querying the underlying * operating system or toolkit depending on the platform. The icon that is returned will therefore depend on a * number of factors including state of the download, platform, registered file types and visual theme. If a file * icon cannot be determined, browser.extension.lastError will contain an error message. * @param downloadId The identifier for the download. */ function getFileIcon(downloadId: number, options?: { /** * The size of the icon. The returned icon will be square with dimensions size * size pixels. The default size * for the icon is 32x32 pixels. */ size?: number; }): Promise; /** Open the downloaded file. */ function open(downloadId: number): Promise; /** Show the downloaded file in its folder in a file manager. */ function show(downloadId: number): Promise; function showDefaultFolder(): void; /** Erase matching DownloadItems from history */ function erase(query: DownloadQuery): Promise; function removeFile(downloadId: number): Promise; /** * Prompt the user to either accept or cancel a dangerous download. `acceptDanger()` does not automatically accept * dangerous downloads. * @deprecated Unsupported on Firefox at this time. */ function acceptDanger(downloadId: number): Promise; /** * Initiate dragging the file to another application. * @deprecated Unsupported on Firefox at this time. */ function drag(downloadId: number): void; /** @deprecated Unsupported on Firefox at this time. */ function setShelfEnabled(enabled: boolean): void; /* downloads events */ /** This event fires with the DownloadItem object when a download begins. */ const onCreated: WebExtEvent<(downloadItem: DownloadItem) => void>; /** * Fires with the `downloadId` when a download is erased from history. * @param downloadId The `id` of the DownloadItem that was erased. */ const onErased: WebExtEvent<(downloadId: number) => void>; /** * When any of a DownloadItem's properties except `bytesReceived` changes, this event fires with the `downloadId` * and an object containing the properties that changed. */ const onChanged: WebExtEvent<(downloadDelta: { /** The `id` of the DownloadItem that changed. */ id: number; /** Describes a change in a DownloadItem's `url`. */ url?: StringDelta; /** Describes a change in a DownloadItem's `filename`. */ filename?: StringDelta; /** Describes a change in a DownloadItem's `danger`. */ danger?: StringDelta; /** Describes a change in a DownloadItem's `mime`. */ mime?: StringDelta; /** Describes a change in a DownloadItem's `startTime`. */ startTime?: StringDelta; /** Describes a change in a DownloadItem's `endTime`. */ endTime?: StringDelta; /** Describes a change in a DownloadItem's `state`. */ state?: StringDelta; canResume?: BooleanDelta; /** Describes a change in a DownloadItem's `paused`. */ paused?: BooleanDelta; /** Describes a change in a DownloadItem's `error`. */ error?: StringDelta; /** Describes a change in a DownloadItem's `totalBytes`. */ totalBytes?: DoubleDelta; /** Describes a change in a DownloadItem's `fileSize`. */ fileSize?: DoubleDelta; exists?: BooleanDelta; }) => void>; } /** * The `browser.events` namespace contains common types used by APIs dispatching events to notify you when something * interesting happens. * * Not allowed in: Content scripts, Devtools pages */ declare namespace browser.events { /* events types */ /** Description of a declarative rule for handling events. */ interface Rule { /** Optional identifier that allows referencing this rule. */ id?: string; /** Tags can be used to annotate rules and perform operations on sets of rules. */ tags?: string[]; /** List of conditions that can trigger the actions. */ conditions: any[]; /** List of actions that are triggered if one of the condtions is fulfilled. */ actions: any[]; /** Optional priority of this rule. Defaults to 100. */ priority?: number; } /** An object which allows the addition and removal of listeners for a Chrome event. */ interface Event { /** * Registers an event listener _callback_ to an event. * @param callback Called when an event occurs. The parameters of this function depend on the type of event. */ addListener(callback: () => void): void; /** * Deregisters an event listener _callback_ from an event. * @param callback Listener that shall be unregistered. */ removeListener(callback: () => void): void; /** * @param callback Listener whose registration status shall be tested. * @returns True if _callback_ is registered to the event. */ hasListener(callback: () => void): boolean; /** @returns True if any event listeners are registered to the event. */ hasListeners(): boolean; /** * Registers rules to handle events. * @param eventName Name of the event this function affects. * @param webViewInstanceId If provided, this is an integer that uniquely identfies the associated * with this function call. * @param rules Rules to be registered. These do not replace previously registered rules. * @deprecated Unsupported on Firefox at this time. */ addRules?(eventName: string, webViewInstanceId: number, rules: Rule[]): Promise; /** * Returns currently registered rules. * @param eventName Name of the event this function affects. * @param webViewInstanceId If provided, this is an integer that uniquely identfies the associated * with this function call. * @param [ruleIdentifiers] If an array is passed, only rules with identifiers contained in this array are * returned. * @deprecated Unsupported on Firefox at this time. */ getRules?(eventName: string, webViewInstanceId: number, ruleIdentifiers?: string[]): Promise; /** * Unregisters currently registered rules. * @param eventName Name of the event this function affects. * @param webViewInstanceId If provided, this is an integer that uniquely identfies the associated * with this function call. * @param [ruleIdentifiers] If an array is passed, only rules with identifiers contained in this array are * unregistered. * @deprecated Unsupported on Firefox at this time. */ removeRules?(eventName: string, webViewInstanceId: number, ruleIdentifiers?: string[]): Promise; } /** Filters URLs for various criteria. See event filtering. All criteria are case sensitive. */ interface UrlFilter { /** * Matches if the host name of the URL contains a specified string. To test whether a host name component has a * prefix 'foo', use hostContains: '.foo'. This matches 'www.foobar.com' and 'foo.com', because an implicit dot * is added at the beginning of the host name. Similarly, hostContains can be used to match against component * suffix ('foo.') and to exactly match against components ('.foo.'). Suffix- and exact-matching for the last * components need to be done separately using hostSuffix, because no implicit dot is added at the end of the * host name. */ hostContains?: string; /** Matches if the host name of the URL is equal to a specified string. */ hostEquals?: string; /** Matches if the host name of the URL starts with a specified string. */ hostPrefix?: string; /** Matches if the host name of the URL ends with a specified string. */ hostSuffix?: string; /** Matches if the path segment of the URL contains a specified string. */ pathContains?: string; /** Matches if the path segment of the URL is equal to a specified string. */ pathEquals?: string; /** Matches if the path segment of the URL starts with a specified string. */ pathPrefix?: string; /** Matches if the path segment of the URL ends with a specified string. */ pathSuffix?: string; /** Matches if the query segment of the URL contains a specified string. */ queryContains?: string; /** Matches if the query segment of the URL is equal to a specified string. */ queryEquals?: string; /** Matches if the query segment of the URL starts with a specified string. */ queryPrefix?: string; /** Matches if the query segment of the URL ends with a specified string. */ querySuffix?: string; /** * Matches if the URL (without fragment identifier) contains a specified string. Port numbers are stripped from * the URL if they match the default port number. */ urlContains?: string; /** * Matches if the URL (without fragment identifier) is equal to a specified string. Port numbers are stripped * from the URL if they match the default port number. */ urlEquals?: string; /** * Matches if the URL (without fragment identifier) matches a specified regular expression. Port numbers are * stripped from the URL if they match the default port number. The regular expressions use the [RE2 * syntax](https://github.com/google/re2/blob/master/doc/syntax.txt). */ urlMatches?: string; /** * Matches if the URL without query segment and fragment identifier matches a specified regular expression. * Port numbers are stripped from the URL if they match the default port number. The regular expressions use * the [RE2 syntax](https://github.com/google/re2/blob/master/doc/syntax.txt). */ originAndPathMatches?: string; /** * Matches if the URL (without fragment identifier) starts with a specified string. Port numbers are stripped * from the URL if they match the default port number. */ urlPrefix?: string; /** * Matches if the URL (without fragment identifier) ends with a specified string. Port numbers are stripped * from the URL if they match the default port number. */ urlSuffix?: string; /** Matches if the scheme of the URL is equal to any of the schemes specified in the array. */ schemes?: string[]; /** * Matches if the port of the URL is contained in any of the specified port lists. For example `[80, 443, * [1000, 1200]]` matches all requests on port 80, 443 and in the range 1000-1200. */ ports?: Array; } } /** Not allowed in: Content scripts, Devtools pages */ declare namespace browser.experiments { /* experiments types */ interface ExperimentAPI { schema: ExperimentURL; parent?: { events?: APIEvents; paths?: APIPaths; script: ExperimentURL; scopes?: APIParentScope[]; }; child?: { paths: APIPaths; script: ExperimentURL; scopes: APIChildScope[]; }; } type ExperimentURL = string; type APIPaths = APIPath[]; type APIPath = string[]; type APIEvents = APIEvent[]; type APIEvent = "startup"; type APIParentScope = "addon_parent" | "content_parent" | "devtools_parent"; type APIChildScope = "addon_child" | "content_child" | "devtools_child"; } /** * The `browser.extension` API has utilities that can be used by any extension page. It includes support for exchanging * messages between an extension and its content scripts or between extensions, as described in detail in Message * Passing. */ declare namespace browser.extension { /* extension types */ /** The type of extension view. */ type ViewType = "tab" | "popup" | "sidebar"; /* extension properties */ /** * Set for the lifetime of a callback if an ansychronous extension api has resulted in an error. If no error has * occured lastError will be `undefined`. */ const lastError: { /** Description of the error that has taken place. */ message: string; } | undefined; /** * True for content scripts running inside incognito tabs, and for extension pages running inside an incognito * process. The latter only applies to extensions with 'split' incognito_behavior. */ const inIncognitoContext: boolean | undefined; /* extension functions */ /** * Converts a relative path within an extension install directory to a fully-qualified URL. * @param path A path to a resource within an extension expressed relative to its install directory. * @returns The fully-qualified URL to the resource. */ function getURL(path: string): string; /** * Returns an array of the JavaScript 'window' objects for each of the pages running inside the current extension. * @returns Array of global objects */ function getViews(fetchProperties?: { /** * The type of view to get. If omitted, returns all views (including background pages and tabs). Valid values: * 'tab', 'popup', 'sidebar'. */ type?: ViewType; /** The window to restrict the search to. If omitted, returns all views. */ windowId?: number; /** Find a view according to a tab id. If this field is omitted, returns all views. */ tabId?: number; }): Window[]; /** * Returns the JavaScript 'window' object for the background page running inside the current extension. Returns * null if the extension has no background page. */ function getBackgroundPage(): Window | void; /** * Retrieves the state of the extension's access to Incognito-mode (as determined by the user-controlled 'Allowed * in Incognito' checkbox. */ function isAllowedIncognitoAccess(): Promise; /** * Retrieves the state of the extension's access to the 'file://' scheme (as determined by the user-controlled * 'Allow access to File URLs' checkbox. */ function isAllowedFileSchemeAccess(): Promise; /** * Sets the value of the ap CGI parameter used in the extension's update URL. This value is ignored for extensions * that are hosted in the browser vendor's store. * @deprecated Unsupported on Firefox at this time. */ function setUpdateUrlData(data: string): void; /* extension events */ /** * Fired when a request is sent from either an extension process or a content script. * @param request The request sent by the calling script. * @param sendResponse Function to call (at most once) when you have a response. The argument should be any * JSON-ifiable object, or undefined if there is no response. If you have more than one `onRequest` listener in * the same document, then only one may send a response. * @deprecated Please use `runtime.onMessage`. */ const onRequest: WebExtEvent<(request: any, sender: runtime.MessageSender, sendResponse: (response?: any) => void) => void> | undefined; /** * Fired when a request is sent from another extension. * @param request The request sent by the calling script. * @param sendResponse Function to call when you have a response. The argument should be any JSON-ifiable object, * or undefined if there is no response. * @deprecated Please use `runtime.onMessageExternal`. */ const onRequestExternal: WebExtEvent<(request: any, sender: runtime.MessageSender, sendResponse: (response?: any) => void) => void> | undefined; } /** * The `browser.extensionTypes` API contains type declarations for WebExtensions. * * Not allowed in: Content scripts, Devtools pages */ declare namespace browser.extensionTypes { /* extensionTypes types */ /** The format of an image. */ type ImageFormat = "jpeg" | "png"; /** Details about the format and quality of an image. */ interface ImageDetails { /** The format of the resulting image. Default is `"jpeg"`. */ format?: ImageFormat; /** * When format is `"jpeg"`, controls the quality of the resulting image. This value is ignored for PNG images. * As quality is decreased, the resulting image will have more visual artifacts, and the number of bytes needed * to store it will decrease. */ quality?: number; } /** The soonest that the JavaScript or CSS will be injected into the tab. */ type RunAt = "document_start" | "document_end" | "document_idle"; /** The origin of the CSS to inject, this affects the cascading order (priority) of the stylesheet. */ type CSSOrigin = "user" | "author"; /** * Details of the script or CSS to inject. Either the code or the file property must be set, but both may not be * set at the same time. */ interface InjectDetails { /** * JavaScript or CSS code to inject. * * **Warning:** * Be careful using the `code` parameter. Incorrect use of it may open your extension to [cross site * scripting](https://en.wikipedia.org/wiki/Cross-site_scripting) attacks. */ code?: string; /** JavaScript or CSS file to inject. */ file?: string; /** * If allFrames is `true`, implies that the JavaScript or CSS should be injected into all frames of current * page. By default, it's `false` and is only injected into the top frame. */ allFrames?: boolean; /** * If matchAboutBlank is true, then the code is also injected in about:blank and about:srcdoc frames if your * extension has access to its parent document. Code cannot be inserted in top-level about:-frames. By default * it is `false`. */ matchAboutBlank?: boolean; /** The ID of the frame to inject the script into. This may not be used in combination with `allFrames`. */ frameId?: number; /** The soonest that the JavaScript or CSS will be injected into the tab. Defaults to "document_idle". */ runAt?: RunAt; /** The css origin of the stylesheet to inject. Defaults to "author". */ cssOrigin?: CSSOrigin; } type Date = string | number | object/*Date*/; type ExtensionFileOrCode = { file: _manifest.ExtensionURL; } | { code: string; }; /** A plain JSON value */ type PlainJSONValue = null | string | number | boolean | _PlainJSONArray | _PlainJSONObject; interface _PlainJSONArray extends Array { } interface _PlainJSONObject { [key: string]: PlainJSONValue; } } /** * Exposes the browser's profiler. * * Permissions: `geckoProfiler` * * Not allowed in: Content scripts, Devtools pages */ declare namespace browser.geckoProfiler { /* geckoProfiler types */ type ProfilerFeature = "java" | "js" | "leaf" | "mainthreadio" | "privacy" | "responsiveness" | "screenshots" | "seqstyle" | "stackwalk" | "tasktracer" | "threads" | "trackopts" | "jstracer" | "jsallocations" | "preferencereads"; type Supports = "windowLength"; /* geckoProfiler functions */ /** Starts the profiler with the specified settings. */ function start(settings: { /** * The maximum size in bytes of the buffer used to store profiling data. A larger value allows capturing a * profile that covers a greater amount of time. */ bufferSize: number; /** * The length of the window of time that's kept in the buffer. Any collected samples are discarded as soon as * they are older than the number of seconds specified in this setting. Zero means no duration restriction. */ windowLength?: number; /** * Interval in milliseconds between samples of profiling data. A smaller value will increase the detail of the * profiles captured. */ interval: number; /** A list of active features for the profiler. */ features: ProfilerFeature[]; /** A list of thread names for which to capture profiles. */ threads?: string[]; }): Promise; /** Stops the profiler and discards any captured profile data. */ function stop(): Promise; /** Pauses the profiler, keeping any profile data that is already written. */ function pause(): Promise; /** Resumes the profiler with the settings that were initially used to start it. */ function resume(): Promise; /** * Gathers the profile data from the current profiling session, and writes it to disk. The returned promise * resolves to a path that locates the created file. * @param fileName The name of the file inside the profile/profiler directory */ function dumpProfileToFile(fileName: string): Promise; /** Gathers the profile data from the current profiling session. */ function getProfile(): Promise; /** * Gathers the profile data from the current profiling session. The returned promise resolves to an array buffer * that contains a JSON string. */ function getProfileAsArrayBuffer(): Promise; /** * Gathers the profile data from the current profiling session. The returned promise resolves to an array buffer * that contains a gzipped JSON string. */ function getProfileAsGzippedArrayBuffer(): Promise; /** * Gets the debug symbols for a particular library. * @param debugName The name of the library's debug file. For example, 'xul.pdb * @param breakpadId The Breakpad ID of the library */ function getSymbols(debugName: string, breakpadId: string): Promise; /* geckoProfiler events */ /** * Fires when the profiler starts/stops running. * @param isRunning Whether the profiler is running or not. Pausing the profiler will not affect this value. */ const onRunning: WebExtEvent<(isRunning: boolean) => void>; } /** * Use the `browser.i18n` infrastructure to implement internationalization across your whole app or extension. */ declare namespace browser.i18n { /* i18n types */ /** * An ISO language code such as `en` or `fr`. For a complete list of languages supported by this method, see * [kLanguageInfoTable](http://src.chromium.org/viewvc/chrome/trunk/src/third_party/cld/languages/internal/languages.cc). * For an unknown language, `und` will be returned, which means that [percentage] of the text is unknown to CLD */ type LanguageCode = string; /* i18n functions */ /** * Gets the accept-languages of the browser. This is different from the locale used by the browser; to get the * locale, use `i18n.getUILanguage`. */ function getAcceptLanguages(): Promise; /** * Gets the localized string for the specified message. If the message is missing, this method returns an empty * string (''). If the format of the `getMessage()` call is wrong — for example, _messageName_ is not a string or * the _substitutions_ array has more than 9 elements — this method returns `undefined`. * @param messageName The name of the message, as specified in the `messages.json` file. * @param [substitutions] Substitution strings, if the message requires any. * @returns Message localized for current locale. */ function getMessage(messageName: string, substitutions?: any): string; /** * Gets the browser UI language of the browser. This is different from `i18n.getAcceptLanguages` which returns the * preferred user languages. * @returns The browser UI language code such as en-US or fr-FR. */ function getUILanguage(): string; /** * Detects the language of the provided text using CLD. * @param text User input string to be translated. */ function detectLanguage(text: string): Promise<{ /** CLD detected language reliability */ isReliable: boolean; /** array of detectedLanguage */ languages: Array<{ language: LanguageCode; /** The percentage of the detected language */ percentage: number; }>; }>; } /** * Use the browser.identity API to get OAuth2 access tokens. * * Permissions: `identity` * * Not allowed in: Content scripts, Devtools pages */ declare namespace browser.identity { /* identity types */ /** An object encapsulating an OAuth account id. */ interface AccountInfo { /** A unique identifier for the account. This ID will not change for the lifetime of the account. */ id: string; } /* identity functions */ /** * Retrieves a list of AccountInfo objects describing the accounts present on the profile. * @deprecated Unsupported on Firefox at this time. */ function getAccounts(): Promise; /** * Gets an OAuth2 access token using the client ID and scopes specified in the oauth2 section of manifest.json. * @deprecated Unsupported on Firefox at this time. */ function getAuthToken(details?: { interactive?: boolean; account?: AccountInfo; scopes?: string[]; }): Promise; /** * Retrieves email address and obfuscated gaia id of the user signed into a profile. * @deprecated Unsupported on Firefox at this time. */ function getProfileUserInfo(): Promise<{ email: string; id: string; }>; /** * Removes an OAuth2 access token from the Identity API's token cache. * @deprecated Unsupported on Firefox at this time. */ function removeCachedAuthToken(details: { token: string; }): Promise<{ email: string; id: string; }>; /** Starts an auth flow at the specified URL. */ function launchWebAuthFlow(details: { url: _manifest.HttpURL; interactive?: boolean; }): Promise; /** * Generates a redirect URL to be used in |launchWebAuthFlow|. * @param [path] The path appended to the end of the generated URL. */ function getRedirectURL(path?: string): string; /* identity events */ /** * Fired when signin state changes for an account on the user's profile. * @deprecated Unsupported on Firefox at this time. */ const onSignInChanged: WebExtEvent<(account: AccountInfo, signedIn: boolean) => void> | undefined; } /** * Use the `browser.idle` API to detect when the machine's idle state changes. * * Permissions: `idle` * * Not allowed in: Content scripts, Devtools pages */ declare namespace browser.idle { /* idle types */ type IdleState = "active" | "idle"; /* idle functions */ /** * Returns "idle" if the user has not generated any input for a specified number of seconds, or "active" otherwise. * @param detectionIntervalInSeconds The system is considered idle if detectionIntervalInSeconds seconds have * elapsed since the last user input detected. */ function queryState(detectionIntervalInSeconds: number): Promise; /** * Sets the interval, in seconds, used to determine when the system is in an idle state for onStateChanged events. * The default interval is 60 seconds. * @param intervalInSeconds Threshold, in seconds, used to determine when the system is in an idle state. */ function setDetectionInterval(intervalInSeconds: number): void; /* idle events */ /** * Fired when the system changes to an active or idle state. The event fires with "idle" if the the user has not * generated any input for a specified number of seconds, and "active" when the user generates input on an idle * system. */ const onStateChanged: WebExtEvent<(newState: IdleState) => void>; } /** * The `browser.management` API provides ways to manage the list of extensions that are installed and running. * * Not allowed in: Content scripts, Devtools pages */ declare namespace browser.management { /* management types */ /** Information about an icon belonging to an extension. */ interface IconInfo { /** * A number representing the width and height of the icon. Likely values include (but are not limited to) 128, * 48, 24, and 16. */ size: number; /** * The URL for this icon image. To display a grayscale version of the icon (to indicate that an extension is * disabled, for example), append `?grayscale=true` to the URL. */ url: string; } /** A reason the item is disabled. */ type ExtensionDisabledReason = "unknown" | "permissions_increase"; /** The type of this extension, 'extension' or 'theme'. */ type ExtensionType = "extension" | "theme"; /** * How the extension was installed. One of * `development`: The extension was loaded unpacked in developer mode, * `normal`: The extension was installed normally via an .xpi file, * `sideload`: The extension was installed by other software on the machine, * `other`: The extension was installed by other means. */ type ExtensionInstallType = "development" | "normal" | "sideload" | "other"; /** Information about an installed extension. */ interface ExtensionInfo { /** The extension's unique identifier. */ id: string; /** The name of this extension. */ name: string; /** A short version of the name of this extension. */ shortName?: string; /** The description of this extension. */ description: string; /** The version of this extension. */ version: string; /** The version name of this extension if the manifest specified one. */ versionName?: string; /** Whether this extension can be disabled or uninstalled by the user. */ mayDisable: boolean; /** Whether it is currently enabled or disabled. */ enabled: boolean; /** A reason the item is disabled. */ disabledReason?: ExtensionDisabledReason; /** The type of this extension, 'extension' or 'theme'. */ type: ExtensionType; /** The URL of the homepage of this extension. */ homepageUrl?: string; /** The update URL of this extension. */ updateUrl?: string; /** The url for the item's options page, if it has one. */ optionsUrl: string; /** * A list of icon information. Note that this just reflects what was declared in the manifest, and the actual * image at that url may be larger or smaller than what was declared, so you might consider using explicit * width and height attributes on img tags referencing these images. See the manifest documentation on icons * for more details. */ icons?: IconInfo[]; /** Returns a list of API based permissions. */ permissions?: string[]; /** Returns a list of host based permissions. */ hostPermissions?: string[]; /** How the extension was installed. */ installType: ExtensionInstallType; } /* management functions */ /** Returns a list of information about installed extensions. */ function getAll(): Promise; /** * Returns information about the installed extension that has the given ID. * @param id The ID from an item of `management.ExtensionInfo`. */ function get(id: _manifest.ExtensionID): Promise; /** Installs and enables a theme extension from the given url. */ function install(options: { /** URL pointing to the XPI file on addons.mozilla.org or similar. */ url: _manifest.HttpURL; /** A hash of the XPI file, using sha256 or stronger. */ hash?: string; }): Promise<{ id: _manifest.ExtensionID; }>; /** * Returns information about the calling extension. Note: This function can be used without requesting the * 'management' permission in the manifest. */ function getSelf(): Promise; /** * Uninstalls the calling extension. Note: This function can be used without requesting the 'management' permission * in the manifest. */ function uninstallSelf(options?: { /** Whether or not a confirm-uninstall dialog should prompt the user. Defaults to false. */ showConfirmDialog?: boolean; /** The message to display to a user when being asked to confirm removal of the extension. */ dialogMessage?: string; }): Promise; /** * Enables or disables the given add-on. * @param id ID of the add-on to enable/disable. * @param enabled Whether to enable or disable the add-on. */ function setEnabled(id: string, enabled: boolean): Promise; /* management events */ /** Fired when an addon has been disabled. */ const onDisabled: WebExtEvent<(info: ExtensionInfo) => void>; /** Fired when an addon has been enabled. */ const onEnabled: WebExtEvent<(info: ExtensionInfo) => void>; /** Fired when an addon has been installed. */ const onInstalled: WebExtEvent<(info: ExtensionInfo) => void>; /** Fired when an addon has been uninstalled. */ const onUninstalled: WebExtEvent<(info: ExtensionInfo) => void>; } /** * This API provides the ability to determine the status of and detect changes in the network connection. This API can * only be used in privileged extensions. * * Permissions: `networkStatus` * * Not allowed in: Content scripts, Devtools pages */ declare namespace browser.networkStatus { /* networkStatus types */ interface NetworkLinkInfo { /** Status of the network link, if "unknown" then link is usually assumed to be "up" */ status: _NetworkLinkInfoStatus; /** If known, the type of network connection that is avialable. */ type: _NetworkLinkInfoType; /** If known, the network id or name. */ id?: string; } /** Status of the network link, if "unknown" then link is usually assumed to be "up" */ type _NetworkLinkInfoStatus = "unknown" | "up" | "down"; /** If known, the type of network connection that is avialable. */ type _NetworkLinkInfoType = "unknown" | "ethernet" | "usb" | "wifi" | "wimax" | "2g" | "3g" | "4g"; /* networkStatus functions */ /** Returns the $(ref:NetworkLinkInfo} of the current network connection. */ function getLinkInfo(): Promise; /* networkStatus events */ /** Fired when the network connection state changes. */ const onConnectionChanged: WebExtEvent<(details: NetworkLinkInfo) => void>; } /** * Permissions: `notifications` * * Not allowed in: Content scripts, Devtools pages */ declare namespace browser.notifications { /* notifications types */ type TemplateType = "basic" | "image" | "list" | "progress"; type PermissionLevel = "granted" | "denied"; interface NotificationItem { /** Title of one item of a list notification. */ title: string; /** Additional details about this item. */ message: string; } interface CreateNotificationOptions { /** Which type of notification to display. */ type: TemplateType; /** A URL to the sender's avatar, app icon, or a thumbnail for image notifications. */ iconUrl?: string; /** A URL to the app icon mask. */ appIconMaskUrl?: string; /** Title of the notification (e.g. sender name for email). */ title: string; /** Main notification content. */ message: string; /** Alternate notification content with a lower-weight font. */ contextMessage?: string; /** Priority ranges from -2 to 2\. -2 is lowest priority. 2 is highest. Zero is default. */ priority?: number; /** A timestamp associated with the notification, in milliseconds past the epoch. */ eventTime?: number; /** * Text and icons for up to two notification action buttons. * @deprecated Unsupported on Firefox at this time. */ buttons?: Array<{ title: string; iconUrl?: string; }>; /** A URL to the image thumbnail for image-type notifications. */ imageUrl?: string; /** Items for multi-item notifications. */ items?: NotificationItem[]; /** Current progress ranges from 0 to 100. */ progress?: number; /** * Whether to show UI indicating that the app will visibly respond to clicks on the body of a notification. */ isClickable?: boolean; } interface UpdateNotificationOptions { /** Which type of notification to display. */ type?: TemplateType; /** A URL to the sender's avatar, app icon, or a thumbnail for image notifications. */ iconUrl?: string; /** A URL to the app icon mask. */ appIconMaskUrl?: string; /** Title of the notification (e.g. sender name for email). */ title?: string; /** Main notification content. */ message?: string; /** Alternate notification content with a lower-weight font. */ contextMessage?: string; /** Priority ranges from -2 to 2\. -2 is lowest priority. 2 is highest. Zero is default. */ priority?: number; /** A timestamp associated with the notification, in milliseconds past the epoch. */ eventTime?: number; /** * Text and icons for up to two notification action buttons. * @deprecated Unsupported on Firefox at this time. */ buttons?: Array<{ title: string; iconUrl?: string; }>; /** A URL to the image thumbnail for image-type notifications. */ imageUrl?: string; /** Items for multi-item notifications. */ items?: NotificationItem[]; /** Current progress ranges from 0 to 100. */ progress?: number; /** * Whether to show UI indicating that the app will visibly respond to clicks on the body of a notification. */ isClickable?: boolean; } /* notifications functions */ /** * Creates and displays a notification. * @param options Contents of the notification. */ function create(options: CreateNotificationOptions): Promise; /** * Creates and displays a notification. * @param notificationId Identifier of the notification. If it is empty, this method generates an id. If it matches * an existing notification, this method first clears that notification before proceeding with the create * operation. * @param options Contents of the notification. */ function create(notificationId: string, options: CreateNotificationOptions): Promise; /** * Updates an existing notification. * @param notificationId The id of the notification to be updated. * @param options Contents of the notification to update to. * @deprecated Unsupported on Firefox at this time. */ function update(notificationId: string, options: UpdateNotificationOptions): Promise; /** * Clears an existing notification. * @param notificationId The id of the notification to be updated. */ function clear(notificationId: string): Promise; /** Retrieves all the notifications. */ function getAll(): Promise<{ [key: string]: CreateNotificationOptions }>; /** * Retrieves whether the user has enabled notifications from this app or extension. * @deprecated Unsupported on Firefox at this time. */ function getPermissionLevel(): Promise; /* notifications events */ /** * Fired when the notification closed, either by the system or by user action. * @param notificationId The notificationId of the closed notification. * @param byUser True if the notification was closed by the user. */ const onClosed: WebExtEvent<(notificationId: string, byUser: boolean) => void>; /** * Fired when the user clicked in a non-button area of the notification. * @param notificationId The notificationId of the clicked notification. */ const onClicked: WebExtEvent<(notificationId: string) => void>; /** * Fired when the user pressed a button in the notification. * @param notificationId The notificationId of the clicked notification. * @param buttonIndex The index of the button clicked by the user. */ const onButtonClicked: WebExtEvent<(notificationId: string, buttonIndex: number) => void>; /** * Fired when the user changes the permission level. * @param level The new permission level. * @deprecated Unsupported on Firefox at this time. */ const onPermissionLevelChanged: WebExtEvent<(level: PermissionLevel) => void> | undefined; /** * Fired when the user clicked on a link for the app's notification settings. * @deprecated Unsupported on Firefox at this time. */ const onShowSettings: WebExtEvent<() => void> | undefined; /** * Fired when the notification is shown. * @param notificationId The notificationId of the shown notification. */ const onShown: WebExtEvent<(notificationId: string) => void>; } /** * Manifest keys: `optional_permissions` * * Not allowed in: Content scripts, Devtools pages */ declare namespace browser.permissions { /* permissions types */ interface Permissions { permissions?: _manifest.OptionalPermission[]; origins?: _manifest.MatchPattern[]; } interface AnyPermissions { permissions?: _manifest.Permission[]; origins?: _manifest.MatchPattern[]; } /* permissions functions */ /** Get a list of all the extension's permissions. */ function getAll(): Promise; /** Check if the extension has the given permissions. */ function contains(permissions: AnyPermissions): Promise; /** * Request the given permissions. * * Not allowed in: Devtools pages */ function request(permissions: Permissions): Promise; /** Relinquish the given permissions. */ function remove(permissions: Permissions): Promise; /* permissions events */ /** * Fired when the extension acquires new permissions. * @deprecated Unsupported on Firefox at this time. */ const onAdded: WebExtEvent<(permissions: Permissions) => void> | undefined; /** * Fired when permissions are removed from the extension. * @deprecated Unsupported on Firefox at this time. */ const onRemoved: WebExtEvent<(permissions: Permissions) => void> | undefined; } /** * Permissions: `privacy` * * Not allowed in: Content scripts, Devtools pages */ declare namespace browser.privacy { } /** * Use the `browser.privacy` API to control usage of the features in the browser that can affect a user's privacy. * * Permissions: `privacy` * * Not allowed in: Content scripts, Devtools pages */ declare namespace browser.privacy.network { /* privacy.network types */ /** The IP handling policy of WebRTC. */ type IPHandlingPolicy = "default" | "default_public_and_private_interfaces" | "default_public_interface_only" | "disable_non_proxied_udp" | "proxy_only"; /* privacy.network properties */ /** * If enabled, the browser attempts to speed up your web browsing experience by pre-resolving DNS entries, * prerendering sites (``), and preemptively opening TCP and SSL connections to servers. * This preference's value is a boolean, defaulting to `true`. */ const networkPredictionEnabled: types.Setting; /** Allow users to enable and disable RTCPeerConnections (aka WebRTC). */ const peerConnectionEnabled: types.Setting; /** * Allow users to specify the media performance/privacy tradeoffs which impacts how WebRTC traffic will be routed * and how much local address information is exposed. This preference's value is of type IPHandlingPolicy, * defaulting to `default`. */ const webRTCIPHandlingPolicy: types.Setting; } /** * Use the `browser.privacy` API to control usage of the features in the browser that can affect a user's privacy. * * Permissions: `privacy` * * Not allowed in: Content scripts, Devtools pages */ declare namespace browser.privacy.services { /* privacy.services properties */ /** * If enabled, the password manager will ask if you want to save passwords. This preference's value is a boolean, * defaulting to `true`. */ const passwordSavingEnabled: types.Setting; } /** * Use the `browser.privacy` API to control usage of the features in the browser that can affect a user's privacy. * * Permissions: `privacy` * * Not allowed in: Content scripts, Devtools pages */ declare namespace browser.privacy.websites { /* privacy.websites types */ /** The mode for tracking protection. */ type TrackingProtectionModeOption = "always" | "never" | "private_browsing"; /** The settings for cookies. */ interface CookieConfig { /** The type of cookies to allow. */ behavior?: _CookieConfigBehavior; /** Whether to create all cookies as nonPersistent (i.e., session) cookies. */ nonPersistentCookies?: boolean; } /** The type of cookies to allow. */ type _CookieConfigBehavior = "allow_all" | "reject_all" | "reject_third_party" | "allow_visited" | "reject_trackers"; /* privacy.websites properties */ /** * If disabled, the browser blocks third-party sites from setting cookies. The value of this preference is of type * boolean, and the default value is `true`. * @deprecated Unsupported on Firefox at this time. */ const thirdPartyCookiesAllowed: types.Setting | undefined; /** * If enabled, the browser sends auditing pings when requested by a website (``). The value of this * preference is of type boolean, and the default value is `true`. */ const hyperlinkAuditingEnabled: types.Setting; /** * If enabled, the browser sends `referer` headers with your requests. Yes, the name of this preference doesn't * match the misspelled header. No, we're not going to change it. The value of this preference is of type boolean, * and the default value is `true`. */ const referrersEnabled: types.Setting; /** * If enabled, the browser attempts to appear similar to other users by reporting generic information to websites. * This can prevent websites from uniquely identifying users. Examples of data that is spoofed include number of * CPU cores, precision of JavaScript timers, the local timezone, and disabling features such as GamePad support, * and the WebSpeech and Navigator APIs. The value of this preference is of type boolean, and the default value is * `false`. */ const resistFingerprinting: types.Setting; /** * If enabled, the browser will associate all data (including cookies, HSTS data, cached images, and more) for any * third party domains with the domain in the address bar. This prevents third party trackers from using directly * stored information to identify you across different websites, but may break websites where you login with a * third party account (such as a Facebook or Google login.) The value of this preference is of type boolean, and * the default value is `false`. */ const firstPartyIsolate: types.Setting; /** * **Available on Windows and ChromeOS only**: If enabled, the browser provides a unique ID to plugins in order to * run protected content. The value of this preference is of type boolean, and the default value is `true`. * @deprecated Unsupported on Firefox at this time. */ const protectedContentEnabled: types.Setting | undefined; /** * Allow users to specify the mode for tracking protection. This setting's value is of type * TrackingProtectionModeOption, defaulting to `private_browsing_only`. */ const trackingProtectionMode: types.Setting; /** * Allow users to specify the default settings for allowing cookies, as well as whether all cookies should be * created as non-persistent cookies. This setting's value is of type CookieConfig. */ const cookieConfig: types.Setting; } /** * Use the browser.proxy API to register proxy scripts in Firefox. Proxy scripts in Firefox are proxy auto-config files * with extra contextual information and support for additional return types. * * Permissions: `proxy` * * Not allowed in: Content scripts, Devtools pages */ declare namespace browser.proxy { /* proxy types */ /** An object which describes proxy settings. */ interface ProxyConfig { /** The type of proxy to use. */ proxyType?: _ProxyConfigProxyType; /** The address of the http proxy, can include a port. */ http?: string; /** Use the http proxy server for all protocols. */ httpProxyAll?: boolean; /** The address of the ftp proxy, can include a port. */ ftp?: string; /** The address of the ssl proxy, can include a port. */ ssl?: string; /** The address of the socks proxy, can include a port. */ socks?: string; /** The version of the socks proxy. */ socksVersion?: number; /** A list of hosts which should not be proxied. */ passthrough?: string; /** A URL to use to configure the proxy. */ autoConfigUrl?: string; /** Do not prompt for authentication if password is saved. */ autoLogin?: boolean; /** Proxy DNS when using SOCKS v5. */ proxyDNS?: boolean; } /** The type of proxy to use. */ type _ProxyConfigProxyType = "none" | "autoDetect" | "system" | "manual" | "autoConfig"; interface _ProxyOnRequestEvent void> { addListener(cb: TCallback, filter: webRequest.RequestFilter, extraInfoSpec?: Array<"requestHeaders">): void; removeListener(cb: TCallback): void; hasListener(cb: TCallback): boolean; } /* proxy properties */ /** Configures proxy settings. This setting's value is an object of type ProxyConfig. */ const settings: types.Setting; /* proxy functions */ /** * Registers the proxy script for the extension. * @deprecated proxy.register has been deprecated and will be removed in Firefox 71. */ function register(url: string): Promise; /** * Unregisters the proxy script for the extension. * @deprecated proxy.unregister has been deprecated and will be removed in Firefox 71. */ function unregister(): Promise; /** * Registers the proxy script for the extension. This is an alias for proxy.register. * @deprecated proxy.registerProxyScript has been deprecated and will be removed in Firefox 71. */ function registerProxyScript(url: string): Promise; /* proxy events */ /** Fired when proxy data is needed for a request. */ const onRequest: _ProxyOnRequestEvent; /** Notifies about errors caused by the invalid use of the proxy API. */ const onError: WebExtEvent<(error: Error) => void>; /** * Please use `proxy.onError`. * @deprecated proxy.onProxyError has been deprecated and will be removed in Firefox 71\. Use proxy.onError instead. */ const onProxyError: WebExtEvent<(error: Error) => void>; } /** * Use the `browser.runtime` API to retrieve the background page, return details about the manifest, and listen for and * respond to events in the app or extension lifecycle. You can also use this API to convert the relative path of URLs * to fully-qualified URLs. * * Allowed in: Proxy scripts */ declare namespace browser.runtime { /* runtime types */ /** An object which allows two way communication with other pages. */ interface Port { name: string; disconnect: () => void; postMessage: (message: object) => void; /** This property will **only** be present on ports passed to onConnect/onConnectExternal listeners. */ sender?: MessageSender; error?: Error; onMessage: WebExtEvent<(response: object) => void>; onDisconnect: WebExtEvent<(port: Port) => void>; } /** An object containing information about the script context that sent a message or request. */ interface MessageSender { /** * The `tabs.Tab` which opened the connection, if any. This property will **only** be present when the * connection was opened from a tab (including content scripts), and **only** if the receiver is an extension, * not an app. */ tab?: tabs.Tab; /** * The frame that opened the connection. 0 for top-level frames, positive for child frames. This will only be * set when `tab` is set. */ frameId?: number; /** The ID of the extension or app that opened the connection, if any. */ id?: string; /** * The URL of the page or frame that opened the connection. If the sender is in an iframe, it will be iframe's * URL not the URL of the page which hosts it. */ url?: string; /** * The TLS channel ID of the page or frame that opened the connection, if requested by the extension or app, * and if available. * @deprecated Unsupported on Firefox at this time. */ tlsChannelId?: string; } /** The operating system the browser is running on. */ type PlatformOs = "mac" | "win" | "android" | "cros" | "linux" | "openbsd"; /** The machine's processor architecture. */ type PlatformArch = "arm" | "x86-32" | "x86-64"; /** An object containing information about the current platform. */ interface PlatformInfo { /** The operating system the browser is running on. */ os: PlatformOs; /** The machine's processor architecture. */ arch: PlatformArch; /** * The native client architecture. This may be different from arch on some platforms. * @deprecated Unsupported on Firefox at this time. */ nacl_arch?: PlatformNaclArch; } /** An object containing information about the current browser. */ interface BrowserInfo { /** The name of the browser, for example 'Firefox'. */ name: string; /** The name of the browser vendor, for example 'Mozilla'. */ vendor: string; /** The browser's version, for example '42.0.0' or '0.8.1pre'. */ version: string; /** The browser's build ID/date, for example '20160101'. */ buildID: string; } /** Result of the update check. */ type RequestUpdateCheckStatus = "throttled" | "no_update" | "update_available"; /** The reason that this event is being dispatched. */ type OnInstalledReason = "install" | "update" | "browser_update"; /** * The reason that the event is being dispatched. 'app_update' is used when the restart is needed because the * application is updated to a newer version. 'os_update' is used when the restart is needed because the browser/OS * is updated to a newer version. 'periodic' is used when the system runs for more than the permitted uptime set in * the enterprise policy. */ type OnRestartRequiredReason = "app_update" | "os_update" | "periodic"; type PlatformNaclArch = any; /* runtime properties */ /** This will be defined during an API method callback if there was an error */ const lastError: { /** Details about the error which occurred. */ message?: string; } | undefined; /** The ID of the extension/app. */ const id: string; /* runtime functions */ /** * Retrieves the JavaScript 'window' object for the background page running inside the current extension/app. If * the background page is an event page, the system will ensure it is loaded before calling the callback. If there * is no background page, an error is set. */ function getBackgroundPage(): Promise; /** * Open your Extension's options page, if possible. * * The precise behavior may depend on your manifest's `options_ui` or `options_page` key, or what the browser * happens to support at the time. * * If your Extension does not declare an options page, or the browser failed to create one for some other reason, * the callback will set `lastError`. */ function openOptionsPage(): Promise; /** * Returns details about the app or extension from the manifest. The object returned is a serialization of the full * manifest file. */ function getManifest(): _manifest.WebExtensionManifest; /** * Converts a relative path within an app/extension install directory to a fully-qualified URL. * @param path A path to a resource within an app/extension expressed relative to its install directory. * @returns The fully-qualified URL to the resource. */ function getURL(path: string): string; /** * Sets the URL to be visited upon uninstallation. This may be used to clean up server-side data, do analytics, and * implement surveys. Maximum 255 characters. * @param [url] URL to be opened after the extension is uninstalled. This URL must have an http: or https: scheme. * Set an empty string to not open a new tab upon uninstallation. */ function setUninstallURL(url?: string): Promise; /** Reloads the app or extension. */ function reload(): void; /** * Requests an update check for this app/extension. * @deprecated Unsupported on Firefox at this time. */ function requestUpdateCheck(): Promise; /** * Restart the device when the app runs in kiosk mode. Otherwise, it's no-op. * @deprecated Unsupported on Firefox at this time. */ function restart(): void; /** * Attempts to connect to connect listeners within an extension/app (such as the background page), or other * extensions/apps. This is useful for content scripts connecting to their extension processes, inter-app/extension * communication, and web messaging. Note that this does not connect to any listeners in a content script. * Extensions may connect to content scripts embedded in tabs via `tabs.connect`. * @param [extensionId] The ID of the extension or app to connect to. If omitted, a connection will be attempted * with your own extension. Required if sending messages from a web page for web messaging. * @returns Port through which messages can be sent and received. The port's `runtime.Port onDisconnect` event is * fired if the extension/app does not exist. */ function connect(extensionId?: string, connectInfo?: { /** Will be passed into onConnect for processes that are listening for the connection event. */ name?: string; /** * Whether the TLS channel ID will be passed into onConnectExternal for processes that are listening for the * connection event. */ includeTlsChannelId?: boolean; }): Port; /** * Connects to a native application in the host machine. * * Not allowed in: Devtools pages * @param application The name of the registered application to connect to. * @returns Port through which messages can be sent and received with the application */ function connectNative(application: string): Port; /** * Sends a single message to event listeners within your extension/app or a different extension/app. Similar to * `runtime.connect` but only sends a single message, with an optional response. If sending to your extension, the * `runtime.onMessage` event will be fired in each page, or `runtime.onMessageExternal`, if a different extension. * Note that extensions cannot send messages to content scripts using this method. To send messages to content * scripts, use `tabs.sendMessage`. * * Allowed in: Proxy scripts */ function sendMessage(message: any, options?: { /** * Whether the TLS channel ID will be passed into onMessageExternal for processes that are listening for the * connection event. * @deprecated Unsupported on Firefox at this time. */ includeTlsChannelId?: boolean; /** If true, the message will be directed to the extension's proxy sandbox. */ toProxyScript?: boolean; }): Promise; /** * Sends a single message to event listeners within your extension/app or a different extension/app. Similar to * `runtime.connect` but only sends a single message, with an optional response. If sending to your extension, the * `runtime.onMessage` event will be fired in each page, or `runtime.onMessageExternal`, if a different extension. * Note that extensions cannot send messages to content scripts using this method. To send messages to content * scripts, use `tabs.sendMessage`. * * Allowed in: Proxy scripts * @param extensionId The ID of the extension/app to send the message to. If omitted, the message will be sent to * your own extension/app. Required if sending messages from a web page for web messaging. */ function sendMessage(extensionId: string, message: any, options?: { /** * Whether the TLS channel ID will be passed into onMessageExternal for processes that are listening for the * connection event. * @deprecated Unsupported on Firefox at this time. */ includeTlsChannelId?: boolean; /** If true, the message will be directed to the extension's proxy sandbox. */ toProxyScript?: boolean; }): Promise; /** * Send a single message to a native application. * * Not allowed in: Devtools pages * @param application The name of the native messaging host. * @param message The message that will be passed to the native messaging host. */ function sendNativeMessage(application: string, message: any): Promise; /** Returns information about the current browser. */ function getBrowserInfo(): Promise; /** Returns information about the current platform. */ function getPlatformInfo(): Promise; /** * Returns a DirectoryEntry for the package directory. * @deprecated Unsupported on Firefox at this time. */ function getPackageDirectoryEntry(): Promise; /* runtime events */ /** * Fired when a profile that has this extension installed first starts up. This event is not fired for incognito * profiles. */ const onStartup: WebExtEvent<() => void>; /** * 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. */ const onInstalled: WebExtEvent<(details: { /** The reason that this event is being dispatched. */ reason: OnInstalledReason; /** * Indicates the previous version of the extension, which has just been updated. This is present only if * 'reason' is 'update'. */ previousVersion?: string; /** Indicates whether the addon is installed as a temporary extension. */ temporary: boolean; /** * Indicates the ID of the imported shared module extension which updated. This is present only if 'reason' is * 'shared_module_update'. * @deprecated Unsupported on Firefox at this time. */ id?: string; }) => void>; /** * Sent to the event page just before it is unloaded. This gives the extension opportunity to do some clean up. * Note that since the page is unloading, any asynchronous operations started while handling this event are not * guaranteed to complete. If more activity for the event page occurs before it gets unloaded the onSuspendCanceled * event will be sent and the page won't be unloaded. * @deprecated Unsupported on Firefox at this time. */ const onSuspend: WebExtEvent<() => void> | undefined; /** * Sent after onSuspend to indicate that the app won't be unloaded after all. * @deprecated Unsupported on Firefox at this time. */ const onSuspendCanceled: WebExtEvent<() => void> | undefined; /** * Fired when an update is available, but isn't installed immediately because the app is currently running. If you * do nothing, the update will be installed the next time the background page gets unloaded, if you want it to be * installed sooner you can explicitly call `runtime.reload`. If your extension is using a persistent background * page, the background page of course never gets unloaded, so unless you call `runtime.reload` manually in * response to this event the update will not get installed until the next time the browser itself restarts. If no * handlers are listening for this event, and your extension has a persistent background page, it behaves as if * `runtime.reload` is called in response to this event. * @param details The manifest details of the available update. */ const onUpdateAvailable: WebExtEvent<(details: { /** The version number of the available update. */ version: string; }) => void>; /** * Fired when an update for the browser is available, but isn't installed immediately because a browser restart is * required. * @deprecated Please use `runtime.onRestartRequired`. */ const onBrowserUpdateAvailable: WebExtEvent<() => void> | undefined; /** Fired when a connection is made from either an extension process or a content script. */ const onConnect: WebExtEvent<(port: Port) => void>; /** Fired when a connection is made from another extension. */ const onConnectExternal: WebExtEvent<(port: Port) => void>; /** * Fired when a message is sent from either an extension process or a content script. * * Allowed in: Proxy scripts * @param message The message sent by the calling script. * @param sendResponse Function to call (at most once) when you have a response. The argument should be any * JSON-ifiable object. If you have more than one `onMessage` listener in the same document, then only one may * send a response. This function becomes invalid when the event listener returns, unless you return true from * the event listener to indicate you wish to send a response asynchronously (this will keep the message * channel open to the other end until `sendResponse` is called). * @returns Return true from the event listener if you wish to call `sendResponse` after the event listener * returns. */ const onMessage: WebExtEvent<(message: any, sender: MessageSender, sendResponse: (response?: any) => void) => boolean | Promise | void>; /** * Fired when a message is sent from another extension/app. Cannot be used in a content script. * @param message The message sent by the calling script. * @param sendResponse Function to call (at most once) when you have a response. The argument should be any * JSON-ifiable object. If you have more than one `onMessage` listener in the same document, then only one may * send a response. This function becomes invalid when the event listener returns, unless you return true from * the event listener to indicate you wish to send a response asynchronously (this will keep the message * channel open to the other end until `sendResponse` is called). * @returns Return true from the event listener if you wish to call `sendResponse` after the event listener * returns. */ const onMessageExternal: WebExtEvent<(message: any, sender: MessageSender, sendResponse: (response?: any) => void) => boolean | Promise | void>; /** * Fired when an app or the device that it runs on needs to be restarted. The app should close all its windows at * its earliest convenient time to let the restart to happen. If the app does nothing, a restart will be enforced * after a 24-hour grace period has passed. Currently, this event is only fired for Chrome OS kiosk apps. * @param reason The reason that the event is being dispatched. * @deprecated Unsupported on Firefox at this time. */ const onRestartRequired: WebExtEvent<(reason: OnRestartRequiredReason) => void> | undefined; } /** * Use the `browser.storage` API to store, retrieve, and track changes to user data. * * Permissions: `storage` */ declare namespace browser.storage { /* storage types */ interface StorageChange { /** The old value of the item, if there was an old value. */ oldValue?: any; /** The new value of the item, if there is a new value. */ newValue?: any; } interface StorageArea { /** * Gets one or more items from storage. * @param [keys] A single key to get, list of keys to get, or a dictionary specifying default values (see * description of the object). An empty list or object will return an empty result object. Pass in `null` * to get the entire contents of storage. */ get(keys?: string | string[] | { [key: string]: any }): Promise<{ [key: string]: any }>; /** * Gets the amount of space (in bytes) being used by one or more items. * @param [keys] A single key or list of keys to get the total usage for. An empty list will return 0\. Pass in * `null` to get the total usage of all of storage. * @deprecated Unsupported on Firefox at this time. */ getBytesInUse?(keys?: string | string[]): Promise; /** * Sets multiple items. * @param items An object which gives each key/value pair to update storage with. Any other key/value pairs in * storage will not be affected. * * Primitive values such as numbers will serialize as expected. Values with a `typeof` `"object"` and * `"function"` will typically serialize to `{}`, with the exception of `Array` (serializes as expected), * `Date`, and `Regex` (serialize using their `String` representation). */ set(items: { [key: string]: any }): Promise; /** * Removes one or more items from storage. * @param keys A single key or a list of keys for items to remove. */ remove(keys: string | string[]): Promise; /** Removes all items from storage. */ clear(): Promise; } /* storage properties */ /** Items in the `sync` storage area are synced by the browser. */ const sync: StorageArea; /** Items in the `local` storage area are local to each machine. */ const local: StorageArea; /** * Items in the `managed` storage area are set by administrators or native applications, and are read-only for the * extension; trying to modify this namespace results in an error. */ const managed: StorageArea; /* storage events */ /** * Fired when one or more items change. * @param changes Object mapping each key that changed to its corresponding `storage.StorageChange` for that item. * @param areaName The name of the storage area (`"sync"`, `"local"` or `"managed"`) the changes are for. */ const onChanged: WebExtEvent<(changes: { [key: string]: StorageChange }, areaName: string) => void>; } /** * Use the `browser.telemetry` API to send telemetry data to the Mozilla Telemetry service. Restricted to Mozilla * privileged webextensions. * * Permissions: `telemetry` * * Not allowed in: Content scripts, Devtools pages */ declare namespace browser.telemetry { /* telemetry types */ /** * Type of scalar: 'count' for numeric values, 'string' for string values, 'boolean' for boolean values. Maps to * `nsITelemetry.SCALAR_TYPE_*`. */ type ScalarType = "count" | "string" | "boolean"; /** Represents registration data for a Telemetry scalar. */ interface ScalarData { kind: ScalarType; /** True if this is a keyed scalar. */ keyed?: boolean; /** True if this data should be recorded on release. */ record_on_release?: boolean; /** * True if this scalar entry is expired. This allows recording it without error, but it will be discarded. */ expired?: boolean; } /** Represents registration data for a Telemetry event. */ interface EventData { /** List of methods for this event entry. */ methods: string[]; /** List of objects for this event entry. */ objects: string[]; /** List of allowed extra keys for this event entry. */ extra_keys: string[]; /** True if this data should be recorded on release. */ record_on_release?: boolean; /** * True if this event entry is expired. This allows recording it without error, but it will be discarded. */ expired?: boolean; } /* telemetry functions */ /** * Submits a custom ping to the Telemetry back-end. See `submitExternalPing` inside TelemetryController.jsm for * more details. * @param type The type of the ping. * @param message The data payload for the ping. * @param options Options object. */ function submitPing(type: string, message: { [key: string]: any }, options: { /** True if the ping should contain the client id. */ addClientId?: boolean; /** True if the ping should contain the environment data. */ addEnvironment?: boolean; /** Set to override the environment data. */ overrideEnvironment?: { [key: string]: any }; /** If true, send the ping using the PingSender. */ usePingSender?: boolean; }): Promise; /** Checks if Telemetry upload is enabled. */ function canUpload(): Promise; /** * Adds the value to the given scalar. * @param name The scalar name. * @param value The numeric value to add to the scalar. Only unsigned integers supported. */ function scalarAdd(name: string, value: number): Promise; /** * Sets the named scalar to the given value. Throws if the value type doesn't match the scalar type. * @param name The scalar name * @param value The value to set the scalar to */ function scalarSet(name: string, value: string | boolean | number | { [key: string]: any }): Promise; /** * Sets the scalar to the maximum of the current and the passed value * @param name The scalar name. * @param value The numeric value to set the scalar to. Only unsigned integers supported. */ function scalarSetMaximum(name: string, value: number): Promise; /** * Record an event in Telemetry. Throws when trying to record an unknown event. * @param category The category name. * @param method The method name. * @param object The object name. * @param [value] An optional string value to record. * @param [extra] An optional object of the form (string -> string). It should only contain registered extra keys. */ function recordEvent(category: string, method: string, object: string, value?: string, extra?: { [key: string]: string }): Promise; /** * Register new scalars to record them from addons. See nsITelemetry.idl for more details. * @param category The unique category the scalars are registered in. * @param data An object that contains registration data for multiple scalars. Each property name is the scalar * name, and the corresponding property value is an object of ScalarData type. */ function registerScalars(category: string, data: { [key: string]: ScalarData }): Promise; /** * Register new events to record them from addons. See nsITelemetry.idl for more details. * @param category The unique category the events are registered in. * @param data An object that contains registration data for 1+ events. Each property name is the category name, * and the corresponding property value is an object of EventData type. */ function registerEvents(category: string, data: { [key: string]: EventData }): Promise; /** * Enable recording of events in a category. Events default to recording disabled. This allows to toggle recording * for all events in the specified category. * @param category The category name. * @param enabled Whether recording is enabled for events in that category. */ function setEventRecordingEnabled(category: string, enabled: boolean): Promise; } /** * The theme API allows customizing of visual elements of the browser. * * Not allowed in: Content scripts, Devtools pages */ declare namespace browser.theme { /* theme types */ /** Info provided in the onUpdated listener. */ interface ThemeUpdateInfo { /** The new theme after update */ theme: object; /** The id of the window the theme has been applied to */ windowId?: number; } /* theme functions */ /** * Returns the current theme for the specified window or the last focused window. * @param [windowId] The window for which we want the theme. */ function getCurrent(windowId?: number): Promise<_manifest.ThemeType>; /** * Make complete updates to the theme. Resolves when the update has completed. * @param details The properties of the theme to update. */ function update(details: _manifest.ThemeType): void; /** * Make complete updates to the theme. Resolves when the update has completed. * @param windowId The id of the window to update. No id updates all windows. * @param details The properties of the theme to update. */ function update(windowId: number, details: _manifest.ThemeType): void; /** * Removes the updates made to the theme. * @param [windowId] The id of the window to reset. No id resets all windows. */ function reset(windowId?: number): void; /* theme events */ /** * Fired when a new theme has been applied * @param updateInfo Details of the theme update */ const onUpdated: WebExtEvent<(updateInfo: ThemeUpdateInfo) => void>; } /** * Contains types used by other schemas. * * Not allowed in: Content scripts, Devtools pages */ declare namespace browser.types { /* types types */ /** * The scope of the Setting. One of * * * `regular`: setting for the regular profile (which is inherited by the incognito profile if not overridden * elsewhere), * * `regular_only`: setting for the regular profile only (not inherited by the incognito profile), * * `incognito_persistent`: setting for the incognito profile that survives browser restarts (overrides regular * preferences), * * `incognito_session_only`: setting for the incognito profile that can only be set during an incognito session * and is deleted when the incognito session ends (overrides regular and incognito_persistent preferences). * * Only `regular` is supported by Firefox at this time. */ type SettingScope = "regular" | "regular_only" | "incognito_persistent" | "incognito_session_only"; /** * One of * * * `not_controllable`: cannot be controlled by any extension * * `controlled_by_other_extensions`: controlled by extensions with higher precedence * * `controllable_by_this_extension`: can be controlled by this extension * * `controlled_by_this_extension`: controlled by this extension */ type LevelOfControl = "not_controllable" | "controlled_by_other_extensions" | "controllable_by_this_extension" | "controlled_by_this_extension"; interface Setting { /** * Gets the value of a setting. * @param details Which setting to consider. */ get(details: { /** Whether to return the value that applies to the incognito session (default false). */ incognito?: boolean; }): Promise<{ /** The value of the setting. */ value: any; /** The level of control of the setting. */ levelOfControl: LevelOfControl; /** * Whether the effective value is specific to the incognito session. * This property will _only_ be present if the `incognito` property in the `details` parameter of `get()` * was true. */ incognitoSpecific?: boolean; }>; /** * Sets the value of a setting. * @param details Which setting to change. */ set(details: { /** * The value of the setting. * Note that every setting has a specific value type, which is described together with the setting. An * extension should _not_ set a value of a different type. */ value: any; /** Where to set the setting (default: regular). */ scope?: SettingScope; }): Promise; /** * Clears the setting, restoring any default value. * @param details Which setting to clear. */ clear(details: { /** Where to clear the setting (default: regular). */ scope?: SettingScope; }): Promise; /** * Fired after the setting changes. * @deprecated Unsupported on Firefox at this time. */ onChange: WebExtEvent<(details: { /** The value of the setting after the change. */ value: any; /** The level of control of the setting. */ levelOfControl: LevelOfControl; /** * Whether the value that has changed is specific to the incognito session. * This property will _only_ be present if the user has enabled the extension in incognito mode. */ incognitoSpecific?: boolean; }) => void>; } } /** * Manifest keys: `user_scripts`, `user_scripts` * * Not allowed in: Devtools pages */ declare namespace browser.userScripts { /* userScripts types */ /** Details of a user script */ interface UserScriptOptions { /** The list of JS files to inject */ js?: extensionTypes.ExtensionFileOrCode[]; /** An opaque user script metadata value */ scriptMetadata?: extensionTypes.PlainJSONValue; matches: _manifest.MatchPattern[]; excludeMatches?: _manifest.MatchPattern[]; includeGlobs?: string[]; excludeGlobs?: string[]; /** * If allFrames is `true`, implies that the JavaScript should be injected into all frames of current page. By * default, it's `false` and is only injected into the top frame. */ allFrames?: boolean; /** * If matchAboutBlank is true, then the code is also injected in about:blank and about:srcdoc frames if your * extension has access to its parent document. Code cannot be inserted in top-level about:-frames. By default * it is `false`. */ matchAboutBlank?: boolean; /** The soonest that the JavaScript will be injected into the tab. Defaults to "document_idle". */ runAt?: extensionTypes.RunAt; } /** An object that represents a user script registered programmatically */ interface RegisteredUserScript { /** Unregister a user script registered programmatically */ unregister(): Promise; } /* userScripts functions */ /** * Register a user script programmatically given its `userScripts.UserScriptOptions`, and resolves to a * `userScripts.RegisteredUserScript` instance */ function register(userScriptOptions: UserScriptOptions): Promise; /* userScripts events */ /** * Event called when a new userScript global has been created * * Allowed in: Content scripts only */ const onBeforeScript: WebExtEvent<(userScript: { /** The userScript metadata (as set in userScripts.register) */ metadata: any; /** The userScript global */ global: any; /** * Exports all the properties of a given plain object as userScript globals * @param sourceObject A plain object whose properties are exported as userScript globals */ defineGlobals: (sourceObject: object) => void; /** * Convert a given value to make it accessible to the userScript code * @param value A value to convert into an object accessible to the userScript */ export: (value: any) => any; }) => void>; } /** * Use the `browser.webNavigation` API to receive notifications about the status of navigation requests in-flight. * * Permissions: `webNavigation` * * Not allowed in: Content scripts, Devtools pages */ declare namespace browser.webNavigation { /* webNavigation types */ /** * Cause of the navigation. The same transition types as defined in the history API are used. These are the same * transition types as defined in the history API except with `"start_page"` in place of `"auto_toplevel"` (for * backwards compatibility). */ type TransitionType = "link" | "typed" | "auto_bookmark" | "auto_subframe" | "manual_subframe" | "generated" | "start_page" | "form_submit" | "reload" | "keyword" | "keyword_generated"; type TransitionQualifier = "client_redirect" | "server_redirect" | "forward_back" | "from_address_bar"; interface EventUrlFilters { url: events.UrlFilter[]; } interface _WebNavigationOnBeforeNavigateEvent void> { addListener(cb: TCallback, filters?: EventUrlFilters): void; removeListener(cb: TCallback): void; hasListener(cb: TCallback): boolean; } interface _WebNavigationOnCommittedEvent void> { addListener(cb: TCallback, filters?: EventUrlFilters): void; removeListener(cb: TCallback): void; hasListener(cb: TCallback): boolean; } interface _WebNavigationOnDOMContentLoadedEvent void> { addListener(cb: TCallback, filters?: EventUrlFilters): void; removeListener(cb: TCallback): void; hasListener(cb: TCallback): boolean; } interface _WebNavigationOnCompletedEvent void> { addListener(cb: TCallback, filters?: EventUrlFilters): void; removeListener(cb: TCallback): void; hasListener(cb: TCallback): boolean; } interface _WebNavigationOnErrorOccurredEvent void> { addListener(cb: TCallback, filters?: EventUrlFilters): void; removeListener(cb: TCallback): void; hasListener(cb: TCallback): boolean; } interface _WebNavigationOnCreatedNavigationTargetEvent void> { addListener(cb: TCallback, filters?: EventUrlFilters): void; removeListener(cb: TCallback): void; hasListener(cb: TCallback): boolean; } interface _WebNavigationOnReferenceFragmentUpdatedEvent void> { addListener(cb: TCallback, filters?: EventUrlFilters): void; removeListener(cb: TCallback): void; hasListener(cb: TCallback): boolean; } interface _WebNavigationOnHistoryStateUpdatedEvent void> { addListener(cb: TCallback, filters?: EventUrlFilters): void; removeListener(cb: TCallback): void; hasListener(cb: TCallback): boolean; } /* webNavigation functions */ /** * Retrieves information about the given frame. A frame refers to an