diff --git a/types/firefox-webext-browser/firefox-webext-browser-tests.ts b/types/firefox-webext-browser/firefox-webext-browser-tests.ts index a82ae7b77138e4..16240175865d71 100644 --- a/types/firefox-webext-browser/firefox-webext-browser-tests.ts +++ b/types/firefox-webext-browser/firefox-webext-browser-tests.ts @@ -11,6 +11,8 @@ browser.test; browser.manifest; // @ts-expect-error browser._manifest; +// @ts-expect-error +browser.trialML; // browser.runtime const port = browser.runtime.connect(); @@ -18,6 +20,59 @@ const port = browser.runtime.connect(); port.postMessage(); port.postMessage({ test: "ok" }); +{ + const manifest = browser.runtime.getManifest(); + + // WebExtensionManifest + const background = manifest.background; + if (background) { + background.preferred_environment = ["service_worker", "document"]; + } + manifest.options_page; // $ExpectType string | undefined + manifest.content_scripts?.every(item => { + item.match_origin_as_fallback; // $ExpectType boolean | undefined + item.world; // $ExpectType ExecutionWorld | undefined + }); + manifest.optional_host_permissions; // $ExpectType string[] | undefined + // @ts-expect-error + manifest.telemetry; + // @ts-expect-error + manifest.chrome_settings_overrides?.search_provider.params; + + // ManifestBase + manifest.manifest_version; // $ExpectType number + manifest.applications?.gecko?.admin_install_only; // $ExpectType boolean | undefined + manifest.applications?.gecko?.data_collection_permissions?.required; // $ExpectType DataCollectionPermission[] | undefined + manifest.developer?.name; // $ExpectType string | undefined +} + +browser.runtime.getContexts({ + contextIds: ["contextId"], + contextTypes: ["BACKGROUND", "POPUP", "SIDE_PANEL", "TAB"], + documentIds: ["documentId"], + documentOrigins: ["documentOrigin"], + documentUrls: ["documentUrl"], + frameIds: [0], + tabIds: [0], + windowIds: [browser.windows.WINDOW_ID_CURRENT], + incognito: true, +}).then(ctxs => { + ctxs.every(ctx => { + ctx.contextId; // $ExpectType string + ctx.contextType = "BACKGROUND"; + ctx.contextType = "POPUP"; + ctx.contextType = "SIDE_PANEL"; + ctx.contextType = "TAB"; + ctx.documentId; // $ExpectType string | undefined + ctx.documentOrigin; // $ExpectType string | undefined + ctx.documentUrl; // $ExpectType string | undefined + ctx.incognito; // $ExpectType boolean + ctx.frameId; // $ExpectType number + ctx.tabId; // $ExpectType number + ctx.windowId; // $ExpectType number + }); +}); + port.onDisconnect.addListener(p => { if (p.error) { console.log(`Disconnected due to an error: ${p.error.message}`); @@ -47,6 +102,8 @@ browser.menus.onClicked.addListener(info => { console.log(info.bookmarkId.toString()); }); +browser.menus.create({ contexts: ["page_action", "browser_action", "action"] }); + browser.proxy.onError.addListener(error => { console.error(`Proxy error: ${error.message}`); }); @@ -109,6 +166,54 @@ browser.tabs.captureVisibleTab(15); browser.tabs.captureVisibleTab(15, { format: "png" }); browser.tabs.captureVisibleTab({ format: "png" }); +browser.tabs.onUpdated.addListener( + (tabId, changeInfo, tab) => { + console.log(tabId, changeInfo.title, tab.groupId); + }, + { properties: ["groupId"], cookieStoreId: "storeId" }, +); +browser.tabGroups.onCreated; +browser.tabGroups.onMoved; +browser.tabGroups.onRemoved.addListener((group, removeInfo) => { + group; // $ExpectType TabGroup + removeInfo.isWindowClosing; // $ExpectType boolean +}); +browser.tabGroups.onUpdated; + +// tabs in tabGroups +browser.tabs.query({ + currentWindow: true, + groupId: browser.tabGroups.TAB_GROUP_ID_NONE, +}); +browser.tabs.group({ + tabIds: [0], + groupId: undefined, + createProperties: { windowId: browser.windows.WINDOW_ID_CURRENT }, +}); +browser.tabGroups.get(0).then(group => { + group.collapsed; // $ExpectType boolean + group.color; // $ExpectType Color + group.id; // $ExpectType number + group.title; // $ExpectType string | undefined + group.windowId; // $ExpectType number +}); +browser.tabGroups.update(0, { + collapsed: true, + color: "red", + title: "title", +}); +browser.tabGroups.query({ + collapsed: false, + color: "blue", + title: "title", + windowId: browser.windows.WINDOW_ID_CURRENT, +}); +browser.tabGroups.move(0, { + index: -1, + windowId: browser.windows.WINDOW_ID_CURRENT, +}); +browser.tabs.ungroup(0); + /* Test SteamFilter */ const filter = browser.webRequest.filterResponseData("1234"); filter.onerror = () => console.log(filter.error); @@ -122,9 +227,103 @@ filter.close(); filter.disconnect(); console.log(filter.status); +// @ts-expect-error +browser.webRequest.onBeforeRequest.addListener(() => {}, { urls: ["url"], types: ["object_subrequest"] }, []); +browser.webRequest.onBeforeRequest.addListener( + details => { + const urlClassification = details.urlClassification; + if (urlClassification) { + urlClassification.firstParty = urlClassification.thirdParty = [ + "any_social_tracking", + "consentmanager", + "antifraud", + ]; + } + }, + { urls: ["url"], types: ["json"] }, + ["blocking", "requestBody"], +); +browser.webRequest.onAuthRequired.addListener( + (details, asyncCallback) => { + details.urlClassification; // $ExpectType UrlClassification | undefined + asyncCallback?.({ cancel: true }); + }, + { urls: ["url"] }, + ["responseHeaders", "blocking", "asyncBlocking"], +); + +browser.storage.sync.QUOTA_BYTES; +browser.storage.sync.QUOTA_BYTES_PER_ITEM; +browser.storage.sync.MAX_ITEMS; +browser.storage.sync.MAX_WRITE_OPERATIONS_PER_HOUR; +browser.storage.sync.MAX_WRITE_OPERATIONS_PER_MINUTE; +browser.storage.sync.MAX_SUSTAINED_WRITE_OPERATIONS_PER_MINUTE; +browser.storage.sync.getKeys().then(keys => { + keys; // $ExpectType string[] +}); +browser.storage.local.QUOTA_BYTES; +browser.storage.local.getKeys().then(keys => { + keys; // $ExpectType string[] +}); +browser.storage.managed.QUOTA_BYTES; +browser.storage.managed.getKeys().then(keys => { + keys; // $ExpectType string[] +}); +browser.storage.session.QUOTA_BYTES; browser.storage.session.get("sessionObject"); +browser.storage.session.getKeys().then(keys => { + keys; // $ExpectType string[] +}); browser.storage.session.set({ "sessionObject": "value" }); +browser.browserAction.setTitle({ title: "actionTitle" }); +browser.browserAction.setIcon({ imageData: undefined, path: undefined }); +browser.browserAction.setPopup({ popup: ".html" }); +browser.browserAction.setBadgeText({ text: "badgeText" }); +browser.browserAction.setBadgeBackgroundColor({ color: [0, 0, 0, 0] }); +browser.browserAction.setBadgeTextColor({ color: [0, 0, 0, 0] }); +browser.browserAction.onUserSettingsChanged.addListener(change => change.isOnToolbar === true); + +browser.contentScripts.register({ matches: [""], matchOriginAsFallback: true, world: "MAIN" }); +browser.contentScripts.register({ matches: [""], world: "ISOLATED" }); + +browser.contextualIdentities.move("storeId", 0); + +browser.cookies.get({ url: "url", name: "name" }).then(cookies => cookies?.partitionKey?.hasCrossSiteAncestor === true); + +browser.declarativeNetRequest.updateDynamicRules({ + addRules: [{ id: 0, condition: { resourceTypes: ["json"] }, action: { type: "allow" } }], +}); +browser.declarativeNetRequest.getDynamicRules({ ruleIds: [0] }); +browser.declarativeNetRequest.getSessionRules({ ruleIds: [0] }); +browser.declarativeNetRequest.updateStaticRules({ rulesetId: "rulesetId" }); +browser.declarativeNetRequest.getDisabledRuleIds({ rulesetId: "rulesetId" }); +browser.declarativeNetRequest.MAX_NUMBER_OF_STATIC_RULESETS; +browser.declarativeNetRequest.MAX_NUMBER_OF_DYNAMIC_RULES; +browser.declarativeNetRequest.MAX_NUMBER_OF_SESSION_RULES; + +browser.geckoProfiler.start({ + bufferSize: 0, + interval: 0, + features: ["cpufreq", "bandwidth", "memory", "tracing", "sandbox", "flows"], +}); + +browser.i18n.getPreferredSystemLanguages().then(languageCodes => { + languageCodes; // $ExpectType string[] +}); + +browser.management.getSelf().then(extensionInfo => { + extensionInfo; // $ExpectType ExtensionInfo + extensionInfo.installType = "admin"; +}); + +browser.permissions.getAll().then(anyPermissions => { + anyPermissions.data_collection; // $ExpectType OptionalDataCollectionPermission[] | undefined +}); +browser.permissions.onAdded.addListener(permissions => { + permissions.data_collection; // $ExpectType OptionalDataCollectionPermission[] | undefined +}); + browser.scripting.executeScript({ target: { tabId: 1 }, func: () => {}, @@ -142,3 +341,72 @@ browser.scripting.executeScript({ args: [0, "", false, [], {}], func: (_n: number, _s: string, _b: boolean, _a: [], _o: {}) => {}, }); +browser.scripting.executeScript({ target: { tabId: 0 }, world: "MAIN" }); +browser.scripting.registerContentScripts([{ id: "scriptId", matchOriginAsFallback: true, world: "MAIN" }]); +browser.scripting.updateContentScripts([{ id: "scriptId", persistAcrossSessions: true, world: "MAIN" }]); + +// @ts-expect-error +browser.telemetry.submitEncryptedPing; + +// MV2 +browser.userScripts.register({ js: [{ file: ".js" }, { code: "document;" }], matches: [""] }).then( + legacyRegisteredUserScript => { + legacyRegisteredUserScript.unregister(); + }, +); +// MV3 +browser.userScripts.register([{ id: "scriptId", js: [{ file: ".js" }, { code: "document;" }], world: "MAIN" }]); +browser.userScripts.register([{ id: "scriptId", js: [{ file: ".js" }, { code: "document;" }], world: "USER_SCRIPT" }]); + +browser.userScripts.update([{ id: "scriptId" }]); +browser.userScripts.unregister({ ids: ["scriptId"] }); +browser.userScripts.getScripts({ ids: ["scriptId"] }).then(scripts => { + scripts.every(script => { + script.id = "scriptId"; + script.js = [{ file: ".js" }, { code: "document;" }]; + script.world = "MAIN"; + }); +}); +browser.userScripts.configureWorld({ worldId: "worldId", csp: "policy", messaging: true }); +browser.userScripts.resetWorldConfiguration("worldId"); +browser.userScripts.getWorldConfigurations().then(propertiesArray => { + propertiesArray.every(properties => { + properties.worldId = "worldId"; + properties.csp = "policy"; + properties.messaging = true; + }); +}); + +browser.commands.openShortcutSettings(); +browser.commands.onCommand.addListener((command, tab) => { + command; // $ExpectType string + tab.active; // $ExpectType boolean +}); + +browser.windows.getAll({ populate: true, windowTypes: ["normal", "popup", "panel", "app", "devtools"] }); + +browser.runtime.onMessage.addListener((message, sender, sendResponse) => { + sender.userScriptWorldId; // $ExpectType string | undefined + return true; +}); +browser.runtime.onPerformanceWarning.addListener(details => { + details.category = "content_script"; + details.severity = "low"; + details.severity = "medium"; + details.severity = "high"; + details.tabId = 0; + details.description; // $ExpectType string +}); + +browser.runtime.onUserScriptConnect.addListener(port => { + port.disconnect(); +}); +browser.runtime.onUserScriptMessage.addListener((message, sender, sendResponse) => { + sender.userScriptWorldId; // $ExpectType string | undefined + return true; +}); + +browser.browserSettings.verticalTabs.get({ incognito: true }); + +browser.alarms.create({ when: 42, delayInMinutes: 4 }); +browser.alarms.create("alarmName", { periodInMinutes: 2 }); diff --git a/types/firefox-webext-browser/index.d.ts b/types/firefox-webext-browser/index.d.ts index c5059f142d508b..50b791a88137b1 100644 --- a/types/firefox-webext-browser/index.d.ts +++ b/types/firefox-webext-browser/index.d.ts @@ -22,7 +22,7 @@ declare namespace browser._manifest { } /** Represents a WebExtension manifest.json file */ - interface WebExtensionManifest { + interface WebExtensionManifest extends ManifestBase { /** Needs at least manifest version 3. */ action?: ActionManifest | undefined; /** Not supported on manifest versions above 2. */ @@ -36,19 +36,20 @@ declare namespace browser._manifest { minimum_chrome_version?: string | undefined; minimum_opera_version?: string | undefined; icons?: _WebExtensionManifestIcons | undefined; + /** The 'split' value is not supported. */ incognito?: _WebExtensionManifestIncognito | undefined; background?: { - page: ExtensionURL; - /** Not supported on manifest versions above 2. */ - persistent?: boolean | undefined; - } | { - scripts: ExtensionURL[]; + service_worker?: ExtensionURL | undefined; + page?: ExtensionURL | undefined; + scripts?: ExtensionURL[] | undefined; + /** Only supported for page/scripts; not for service_worker yet, see bug 1775574 */ type?: _UndefinedType | undefined; /** Not supported on manifest versions above 2. */ persistent?: boolean | undefined; - } | { - service_worker: ExtensionURL; + preferred_environment?: _PreferredEnvironment[] | undefined; } | undefined; + /** Alias property for options_ui.page, ignored when options_ui.page is set. When using this property the options page is always opened in a new tab. */ + options_page?: ExtensionURL | undefined; options_ui?: _WebExtensionManifestOptionsUi | undefined; content_scripts?: ContentScript[] | undefined; content_security_policy?: string | { @@ -59,6 +60,8 @@ declare namespace browser._manifest { granted_host_permissions?: boolean | undefined; /** Needs at least manifest version 3. */ host_permissions?: MatchPattern[] | undefined; + /** Needs at least manifest version 3. */ + optional_host_permissions?: MatchPattern[] | undefined; optional_permissions?: OptionalPermissionOrOrigin[] | undefined; web_accessible_resources?: | string[] @@ -70,7 +73,6 @@ declare namespace browser._manifest { | undefined; hidden?: boolean | undefined; page_action?: _WebExtensionManifestPageAction | undefined; - telemetry?: _WebExtensionManifestTelemetry | undefined; theme_experiment?: ThemeExperiment | undefined; /** Not supported on manifest versions above 2. */ user_scripts?: _WebExtensionManifestUserScripts | undefined; @@ -80,21 +82,6 @@ declare namespace browser._manifest { omnibox?: _WebExtensionManifestOmnibox | undefined; sidebar_action?: _WebExtensionManifestSidebarAction | undefined; chrome_url_overrides?: _WebExtensionManifestChromeUrlOverrides | undefined; - manifest_version: number; - /** - * The applications property is deprecated, please use 'browser_specific_settings' - * Not supported on manifest versions above 2. - */ - applications?: DeprecatedApplications | undefined; - browser_specific_settings?: BrowserSpecificSettings | undefined; - name: string; - short_name?: string | undefined; - description?: string | undefined; - author?: string | undefined; - version: string; - homepage_url?: string | undefined; - install_origins?: string[] | undefined; - developer?: _WebExtensionManifestDeveloper | undefined; } type OptionalPermission = OptionalPermissionNoPrompt | _OptionalPermission; @@ -105,6 +92,14 @@ declare namespace browser._manifest { type Permission = string | PermissionNoPrompt | OptionalPermission | "declarativeNetRequest"; + type OptionalOnlyPermission = "userScripts"; + + type CommonDataCollectionPermission = _CommonDataCollectionPermission; + + type DataCollectionPermission = CommonDataCollectionPermission | "none"; + + type OptionalDataCollectionPermission = CommonDataCollectionPermission | "technicalAndInteraction"; + /** Represents a protocol handler definition. */ interface ProtocolHandler { /** @@ -130,6 +125,7 @@ declare namespace browser._manifest { */ applications?: DeprecatedApplications | undefined; browser_specific_settings?: BrowserSpecificSettings | undefined; + /** Name must be at least 2, and should be at most 75 characters. */ name: string; short_name?: string | undefined; description?: string | undefined; @@ -141,65 +137,15 @@ declare namespace browser._manifest { } /** Represents a WebExtension language pack manifest.json file */ - interface WebExtensionLangpackManifest { + interface WebExtensionLangpackManifest extends ManifestBase { langpack_id: string; languages: _WebExtensionLangpackManifestLanguages; sources?: _WebExtensionLangpackManifestSources | undefined; - manifest_version: number; - /** - * The applications property is deprecated, please use 'browser_specific_settings' - * Not supported on manifest versions above 2. - */ - applications?: DeprecatedApplications | undefined; - browser_specific_settings?: BrowserSpecificSettings | undefined; - name: string; - short_name?: string | undefined; - description?: string | undefined; - author?: string | undefined; - version: string; - homepage_url?: string | undefined; - install_origins?: string[] | undefined; - developer?: _WebExtensionLangpackManifestDeveloper | undefined; } /** Represents a WebExtension dictionary manifest.json file */ - interface WebExtensionDictionaryManifest { + interface WebExtensionDictionaryManifest extends ManifestBase { dictionaries: _WebExtensionDictionaryManifestDictionaries; - manifest_version: number; - /** - * The applications property is deprecated, please use 'browser_specific_settings' - * Not supported on manifest versions above 2. - */ - applications?: DeprecatedApplications | undefined; - browser_specific_settings?: BrowserSpecificSettings | undefined; - name: string; - short_name?: string | undefined; - description?: string | undefined; - author?: string | undefined; - version: string; - homepage_url?: string | undefined; - install_origins?: string[] | undefined; - developer?: _WebExtensionDictionaryManifestDeveloper | undefined; - } - - /** Represents a WebExtension site permissions manifest.json file */ - interface WebExtensionSitePermissionsManifest { - site_permissions: SitePermission[]; - install_origins?: [string] | undefined; - manifest_version: number; - /** - * The applications property is deprecated, please use 'browser_specific_settings' - * Not supported on manifest versions above 2. - */ - applications?: DeprecatedApplications | undefined; - browser_specific_settings?: BrowserSpecificSettings | undefined; - name: string; - short_name?: string | undefined; - description?: string | undefined; - author?: string | undefined; - version: string; - homepage_url?: string | undefined; - developer?: _WebExtensionSitePermissionsManifestDeveloper | undefined; } interface ThemeIcons { @@ -211,12 +157,10 @@ declare namespace browser._manifest { size: number; } - type OptionalPermissionOrOrigin = OptionalPermission | MatchPattern; + type OptionalPermissionOrOrigin = OptionalPermission | OptionalOnlyPermission | MatchPattern; type PermissionOrOrigin = Permission | MatchPattern; - type SitePermission = _SitePermission; - type HttpURL = string; type ExtensionURL = string; @@ -232,6 +176,12 @@ declare namespace browser._manifest { update_url?: string | undefined; strict_min_version?: string | undefined; strict_max_version?: string | undefined; + admin_install_only?: boolean | undefined; + data_collection_permissions?: { + required?: DataCollectionPermission[] | undefined; + optional?: OptionalDataCollectionPermission[] | undefined; + has_previous_consent?: boolean | undefined; + } | undefined; } interface GeckoAndroidSpecificProperties { @@ -252,7 +202,7 @@ declare namespace browser._manifest { type MatchPattern = MatchPatternRestricted | MatchPatternUnestricted | ""; - /** Same as MatchPattern above, but excludes */ + /** Same as MatchPattern above, but excludes <all_urls>. */ type MatchPatternRestricted = string; /** @@ -277,11 +227,17 @@ declare namespace browser._manifest { */ all_frames?: boolean | undefined; /** - * 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`. + * If match_about_blank is true, then the code is also injected in about:blank and about:srcdoc frames if your extension has access to its parent document. Ignored if match_origin_as_fallback is specified. By default it is `false`. */ match_about_blank?: boolean | undefined; + /** + * If match_origin_as_fallback is true, then the code is also injected in about:, data:, blob: when their origin matches the pattern in 'matches', even if the actual document origin is opaque (due to the use of CSP sandbox or iframe sandbox). Match patterns in 'matches' must specify a wildcard path glob. By default it is `false`. + */ + match_origin_as_fallback?: boolean | undefined; /** The soonest that the JavaScript or CSS will be injected into the tab. Defaults to "document_idle". */ run_at?: extensionTypes.RunAt | undefined; + /** The JavaScript world for a script to execute within. Defaults to "ISOLATED". */ + world?: extensionTypes.ExecutionWorld | undefined; } type IconPath = { @@ -327,7 +283,7 @@ declare namespace browser._manifest { } /** Contents of manifest.json for a static theme */ - interface ThemeManifest { + interface ThemeManifest extends ManifestBase { theme: ThemeType; dark_theme?: ThemeType | undefined; default_locale?: string | undefined; @@ -371,10 +327,13 @@ declare namespace browser._manifest { [key: number]: ExtensionFileUrl; } - type _WebExtensionManifestIncognito = "not_allowed" | "spanning"; + /** The 'split' value is not supported. */ + type _WebExtensionManifestIncognito = "not_allowed" | "spanning" | "split"; type _UndefinedType = "module" | "classic"; + type _PreferredEnvironment = "service_worker" | "document"; + interface _WebExtensionManifestOptionsUi { page: ExtensionURL; /** Defaults to true in Manifest V2; Deprecated in Manifest V3. */ @@ -410,43 +369,11 @@ declare namespace browser._manifest { key: _WebExtensionManifestTelemetryPublicKeyKey; } - interface _WebExtensionManifestTelemetry { - ping_type: string; - schemaNamespace: string; - public_key: _WebExtensionManifestTelemetryPublicKey; - study_name?: string | undefined; - pioneer_id?: boolean | undefined; - } - /** Not supported on manifest versions above 2. */ interface _WebExtensionManifestUserScripts { api_script?: ExtensionURL | undefined; } - /** 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"; - - interface _WebExtensionManifestChromeSettingsOverridesSearchProviderParams { - /** A url parameter name */ - name: string; - /** The type of param can be either "purpose" or "pref". */ - condition?: _WebExtensionManifestChromeSettingsOverridesSearchProviderParamsCondition | undefined; - /** The preference to retrieve the value from. */ - pref?: string | undefined; - /** The context that initiates a search, required if condition is "purpose". */ - purpose?: _WebExtensionManifestChromeSettingsOverridesSearchProviderParamsPurpose | undefined; - /** A url parameter value. */ - value?: string | undefined; - } - interface _WebExtensionManifestChromeSettingsOverridesSearchProvider { name: string; keyword?: string | string[] | undefined; @@ -469,6 +396,7 @@ declare namespace browser._manifest { instant_url_post_params?: string | undefined; /** @deprecated Unsupported on Firefox at this time. */ image_url_post_params?: string | undefined; + /** @deprecated Unsupported on Firefox at this time. */ search_form?: string | undefined; /** @deprecated Unsupported on Firefox at this time. */ alternate_urls?: string[] | undefined; @@ -478,10 +406,6 @@ declare namespace browser._manifest { encoding?: string | undefined; /** Sets the default engine to a built-in engine only. */ is_default?: boolean | undefined; - /** - * 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?: _WebExtensionManifestChromeSettingsOverridesSearchProviderParams[] | undefined; } interface _WebExtensionManifestChromeSettingsOverrides { @@ -528,11 +452,6 @@ declare namespace browser._manifest { history?: ExtensionURL | undefined; } - interface _WebExtensionManifestDeveloper { - name?: string | undefined; - url?: string | undefined; - } - type _OptionalPermission = | "browserSettings" | "browsingData" @@ -577,13 +496,28 @@ declare namespace browser._manifest { | "idle" | "scripting" | "webRequest" + | "webRequestAuthProvider" | "webRequestBlocking" | "webRequestFilterResponse" | "webRequestFilterResponse.serviceWorkerScript" | "menus.overrideContext" | "search" + | "tabGroups" | "activeTab"; + type _CommonDataCollectionPermission = + | "authenticationInfo" + | "bookmarksInfo" + | "browsingActivity" + | "financialAndPaymentInfo" + | "healthInfo" + | "locationInfo" + | "personalCommunications" + | "personallyIdentifyingInfo" + | "searchTerms" + | "websiteActivity" + | "websiteContent"; + type _ProtocolHandlerProtocol = | "bitcoin" | "dat" @@ -638,27 +572,10 @@ declare namespace browser._manifest { }; } - interface _WebExtensionLangpackManifestDeveloper { - name?: string | undefined; - url?: string | undefined; - } - interface _WebExtensionDictionaryManifestDictionaries { [key: string]: string; } - interface _WebExtensionDictionaryManifestDeveloper { - name?: string | undefined; - url?: string | undefined; - } - - interface _WebExtensionSitePermissionsManifestDeveloper { - name?: string | undefined; - url?: string | undefined; - } - - type _SitePermission = "midi" | "midi-sysex"; - interface _ThemeTypeImages { additional_backgrounds?: ImageDataOrExtensionURL[] | undefined; /** @@ -862,13 +779,13 @@ declare namespace browser.alarms { * 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: _CreateAlarmInfo): void; + function create(alarmInfo: _CreateAlarmInfo): Promise; /** * 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: _CreateAlarmInfo): void; + function create(name: string, alarmInfo: _CreateAlarmInfo): Promise; /** * Retrieves details about the specified alarm. @@ -1200,23 +1117,15 @@ declare namespace browser.browserAction { /** * Specifies to which tab or window the value should be set, or from which one it should be retrieved. If no tab nor window is specified, the global value is set or retrieved. */ - interface _SetTitleDetails { + interface _SetTitleDetails extends Details { /** The string the browser action should display when moused over. */ title: string | null; - /** - * When setting a value, it will be specific to the specified tab, and will automatically reset when the tab navigates. When getting, specifies the tab to get the value from; if there is no tab-specific value, the window one will be inherited. - */ - tabId?: number | undefined; - /** - * When setting a value, it will be specific to the specified window. When getting, specifies the window to get the value from; if there is no window-specific value, the global one will be inherited. - */ - windowId?: number | undefined; } /** * Specifies to which tab or window the value should be set, or from which one it should be retrieved. If no tab nor window is specified, the global value is set or retrieved. */ - interface _SetIconDetails { + interface _SetIconDetails extends Details { /** * Either an ImageData object or a dictionary {size -> ImageData} representing icon to be set. If the icon is specified as a dictionary, the actual image to be used is chosen depending on screen's pixel density. If the number of image pixels that fit into one screen space unit equals `scale`, then image with size `scale` * 19 will be selected. Initially only scales 1 and 2 will be supported. At least one image must be specified. Note that 'details.imageData = foo' is equivalent to 'details.imageData = {'19': foo}' */ @@ -1229,76 +1138,36 @@ declare namespace browser.browserAction { path?: string | { [key: number]: string; } | undefined; - /** - * When setting a value, it will be specific to the specified tab, and will automatically reset when the tab navigates. When getting, specifies the tab to get the value from; if there is no tab-specific value, the window one will be inherited. - */ - tabId?: number | undefined; - /** - * When setting a value, it will be specific to the specified window. When getting, specifies the window to get the value from; if there is no window-specific value, the global one will be inherited. - */ - windowId?: number | undefined; } /** * Specifies to which tab or window the value should be set, or from which one it should be retrieved. If no tab nor window is specified, the global value is set or retrieved. */ - interface _SetPopupDetails { + interface _SetPopupDetails extends Details { /** The html file to show in a popup. If set to the empty string (''), no popup is shown. */ popup: string | null; - /** - * When setting a value, it will be specific to the specified tab, and will automatically reset when the tab navigates. When getting, specifies the tab to get the value from; if there is no tab-specific value, the window one will be inherited. - */ - tabId?: number | undefined; - /** - * When setting a value, it will be specific to the specified window. When getting, specifies the window to get the value from; if there is no window-specific value, the global one will be inherited. - */ - windowId?: number | undefined; } /** * Specifies to which tab or window the value should be set, or from which one it should be retrieved. If no tab nor window is specified, the global value is set or retrieved. */ - interface _SetBadgeTextDetails { + interface _SetBadgeTextDetails extends Details { /** Any number of characters can be passed, but only about four can fit in the space. */ text: string | null; - /** - * When setting a value, it will be specific to the specified tab, and will automatically reset when the tab navigates. When getting, specifies the tab to get the value from; if there is no tab-specific value, the window one will be inherited. - */ - tabId?: number | undefined; - /** - * When setting a value, it will be specific to the specified window. When getting, specifies the window to get the value from; if there is no window-specific value, the global one will be inherited. - */ - windowId?: number | undefined; } /** * Specifies to which tab or window the value should be set, or from which one it should be retrieved. If no tab nor window is specified, the global value is set or retrieved. */ - interface _SetBadgeBackgroundColorDetails { + interface _SetBadgeBackgroundColorDetails extends Details { color: ColorValue; - /** - * When setting a value, it will be specific to the specified tab, and will automatically reset when the tab navigates. When getting, specifies the tab to get the value from; if there is no tab-specific value, the window one will be inherited. - */ - tabId?: number | undefined; - /** - * When setting a value, it will be specific to the specified window. When getting, specifies the window to get the value from; if there is no window-specific value, the global one will be inherited. - */ - windowId?: number | undefined; } /** * Specifies to which tab or window the value should be set, or from which one it should be retrieved. If no tab nor window is specified, the global value is set or retrieved. */ - interface _SetBadgeTextColorDetails { + interface _SetBadgeTextColorDetails extends Details { color: ColorValue; - /** - * When setting a value, it will be specific to the specified tab, and will automatically reset when the tab navigates. When getting, specifies the tab to get the value from; if there is no tab-specific value, the window one will be inherited. - */ - tabId?: number | undefined; - /** - * When setting a value, it will be specific to the specified window. When getting, specifies the window to get the value from; if there is no window-specific value, the global one will be inherited. - */ - windowId?: number | undefined; } /** An object with information about the popup to open. */ @@ -1390,6 +1259,11 @@ declare namespace browser.browserAction { * Fired when a browser action icon is clicked. This event will not fire if the browser action has a popup. */ const onClicked: WebExtEvent<(tab: tabs.Tab, info?: OnClickData) => void>; + + /** + * Fired when user-specified settings relating to an extension's action change. + */ + const onUserSettingsChanged: WebExtEvent<(change: browser.action._GetUserSettingsReturnUserSettings) => void>; } /** @@ -1483,6 +1357,9 @@ declare namespace browser.browserSettings { * This boolean setting controls whether zoom is applied on a per-site basis or to the current tab only. If privacy.resistFingerprinting is true, this setting has no effect and zoom is applied to the current tab only. */ const zoomSiteSpecific: types.Setting; + + /** This boolean setting controls whether vertical tabs are enabled. */ + const verticalTabs: types.Setting; } /** @@ -1731,11 +1608,17 @@ declare namespace browser.contentScripts { */ allFrames?: boolean | undefined; /** - * 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`. + * 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. Ignored if matchOriginAsFallback is specified. By default it is `false`. */ matchAboutBlank?: boolean | undefined; + /** + * If matchOriginAsFallback is true, then the code is also injected in about:, data:, blob: when their origin matches the pattern in 'matches', even if the actual document origin is opaque (due to the use of CSP sandbox or iframe sandbox). Match patterns in 'matches' must specify a wildcard path glob. By default it is `false`. + */ + matchOriginAsFallback?: boolean | undefined; /** The soonest that the JavaScript or CSS will be injected into the tab. Defaults to "document_idle". */ runAt?: extensionTypes.RunAt | undefined; + /** The JavaScript world for a script to execute within. Defaults to "ISOLATED". */ + world?: extensionTypes.ExecutionWorld | undefined; /** limit the set of matched tabs to those that belong to the given cookie store id */ cookieStoreId?: string[] | string | undefined; } @@ -1844,7 +1727,14 @@ declare namespace browser.contextualIdentities { function update(cookieStoreId: string, details: _UpdateDetails): Promise; /** - * Deletes a contetual identity by its cookie Store ID. + * Reorder one or more contextual identities by their cookieStoreIDs to a given position. + * @param cookieStoreId The ID or list of IDs of the contextual identity cookie stores. + * @param position The position the contextual identity should move to. + */ + function move(cookieStoreId: string | string[], position: number): Promise; + + /** + * Deletes a contextual identity by its cookie Store ID. * @param cookieStoreId The ID of the contextual identity cookie store. */ function remove(cookieStoreId: string): Promise; @@ -1873,6 +1763,7 @@ declare namespace browser.cookies { * 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 = + | "unspecified" | "no_restriction" | "lax" | "strict"; @@ -1883,6 +1774,8 @@ declare namespace browser.cookies { interface PartitionKey { /** The first-party URL of the cookie, if the cookie is in storage partitioned by the top-level site. */ topLevelSite?: string | undefined; + /** Whether or not the cookie is in a third-party context, respecting ancestor chains. */ + hasCrossSiteAncestor?: boolean | undefined; } /** Represents information about an HTTP cookie. */ @@ -2122,7 +2015,7 @@ declare namespace browser.cookies { */ declare namespace browser.declarativeNetRequest { /* declarativeNetRequest types */ - /** How the requested resource will be used. Comparable to the webRequest.ResourceType type. */ + /** How the requested resource will be used. Comparable to the webRequest.ResourceType type. object_subrequest is unsupported. */ type ResourceType = | "main_frame" | "sub_frame" @@ -2143,6 +2036,7 @@ declare namespace browser.declarativeNetRequest { | "imageset" | "web_manifest" | "speculative" + | "json" | "other"; /** Describes the reason why a given regular expression isn't supported. */ @@ -2186,7 +2080,7 @@ declare namespace browser.declarativeNetRequest { interface Rule { /** An id which uniquely identifies a rule. Mandatory and should be >= 1. */ id: number; - /** Rule priority. Defaults to 1\. When specified, should be >= 1 */ + /** Rule priority. Defaults to 1. When specified, should be >= 1 */ priority?: number | undefined; /** The condition under which this rule is triggered. */ condition: _RuleCondition; @@ -2194,6 +2088,11 @@ declare namespace browser.declarativeNetRequest { action: _RuleAction; } + interface GetRulesFilter { + /** If specified, only rules with matching IDs are included. */ + ruleIds?: number[] | undefined; + } + /** The new scheme for the request. */ type _URLTransformScheme = | "http" @@ -2362,6 +2261,16 @@ declare namespace browser.declarativeNetRequest { enableRulesetIds?: string[] | undefined; } + interface _UpdateStaticRulesOptions { + rulesetId: string; + disableRuleIds?: number[] | undefined; + enableRuleIds?: number[] | undefined; + } + + interface _GetDisabledRuleIdsOptions { + rulesetId: string; + } + interface _IsRegexSupportedReturnResult { /** Whether the given regex is supported */ isSupported: boolean; @@ -2422,14 +2331,23 @@ declare namespace browser.declarativeNetRequest { */ const MAX_NUMBER_OF_STATIC_RULESETS: number; + /** The maximum number of static rules that can be disabled on each static ruleset. */ + const MAX_NUMBER_OF_DISABLED_STATIC_RULES: number; + /** The maximum number of static Rulesets an extension can enable at any one time. */ const MAX_NUMBER_OF_ENABLED_STATIC_RULESETS: number; /** - * The maximum number of dynamic and session rules an extension can add. NOTE: in the Firefox we are enforcing this limit to the session and dynamic rules count separately, instead of enforcing it to the rules count for both combined as the Chrome implementation does. + * @deprecated Deprecated property returning the maximum number of dynamic and session rules an extension can add, replaced by MAX_NUMBER_OF_DYNAMIC_RULES/MAX_NUMBER_OF_SESSION_RULES. */ const MAX_NUMBER_OF_DYNAMIC_AND_SESSION_RULES: number; + /** The maximum number of dynamic rules an extension can add. */ + const MAX_NUMBER_OF_DYNAMIC_RULES: number; + + /** The maximum number of session rules an extension can add. */ + const MAX_NUMBER_OF_SESSION_RULES: number; + /** * The maximum number of regular expression rules that an extension can add. This limit is evaluated separately for the set of session rules, dynamic rules and those specified in the rule_resources file. */ @@ -2452,17 +2370,31 @@ declare namespace browser.declarativeNetRequest { /** Returns the ids for the current set of enabled static rulesets. */ function getEnabledRulesets(): Promise; - /** Returns the ids for the current set of enabled static rulesets. */ + /** Modifies the static rulesets enabled/disabled state. */ function updateEnabledRulesets(updateRulesetOptions: _UpdateEnabledRulesetsUpdateRulesetOptions): Promise; + /** + * Modified individual static rules enabled/disabled state. Changes to rules belonging to a disabled ruleset will take effect when the ruleset becomes enabled. + */ + function updateStaticRules(options: _UpdateStaticRulesOptions): Promise; + /** Returns the remaining number of static rules an extension can enable */ function getAvailableStaticRuleCount(): Promise; - /** Returns the current set of dynamic rules for the extension. */ - function getDynamicRules(): Promise; + /** Returns the list of individual disabled static rules from a given static ruleset id. */ + function getDisabledRuleIds(options?: _GetDisabledRuleIdsOptions): Promise; - /** Returns the current set of session scoped rules for the extension. */ - function getSessionRules(): Promise; + /** + * Returns the current set of dynamic rules for the extension. + * @param filter An object to filter the set of dynamic rules for the extension. + */ + function getDynamicRules(filter?: GetRulesFilter): Promise; + + /** + * Returns the current set of session scoped rules for the extension. + * @param filter An object to filter the set of session scoped rules for the extension. + */ + function getSessionRules(filter?: GetRulesFilter): Promise; /** Checks if the given regular expression will be supported as a 'regexFilter' rule condition. */ function isRegexSupported(regexOptions: _IsRegexSupportedRegexOptions): Promise<_IsRegexSupportedReturnResult>; @@ -2910,7 +2842,7 @@ declare namespace browser.events { /** * 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 webViewInstanceId If provided, this is an integer that uniquely identfies the <webview> 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. */ @@ -2918,7 +2850,7 @@ declare namespace browser.events { /** * 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 webViewInstanceId If provided, this is an integer that uniquely identfies the <webview> 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. */ @@ -2926,7 +2858,7 @@ declare namespace browser.events { /** * 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 webViewInstanceId If provided, this is an integer that uniquely identfies the <webview> 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. */ @@ -3167,7 +3099,7 @@ declare namespace browser.extensionTypes { /** The scale of the resulting image. Defaults to `devicePixelRatio`. */ scale?: number | undefined; /** - * If true, temporarily resets the scroll position of the document to 0\. Only takes effect if rect is also specified. + * If true, temporarily resets the scroll position of the document to 0. Only takes effect if rect is also specified. */ resetScrollPosition?: boolean | undefined; } @@ -3178,6 +3110,13 @@ declare namespace browser.extensionTypes { | "document_end" | "document_idle"; + /** + * The JavaScript world for a script to execute within. `ISOLATED` is the default execution environment of content scripts, `MAIN` is the web page's execution environment. + */ + type ExecutionWorld = + | "ISOLATED" + | "MAIN"; + /** The origin of the CSS to inject, this affects the cascading order (priority) of the stylesheet. */ type CSSOrigin = "user" | "author"; @@ -3271,7 +3210,12 @@ declare namespace browser.geckoProfiler { | "processcpu" | "power" | "responsiveness" - | "cpufreq"; + | "cpufreq" + | "bandwidth" + | "memory" + | "tracing" + | "sandbox" + | "flows"; type Supports = "windowLength"; @@ -3382,6 +3326,12 @@ declare namespace browser.i18n { */ function getMessage(messageName: string, substitutions?: any): string; + /** + * Gets the preferred locales of the operating system. This is different from the locales set in the browser; to get those, use `i18n.getAcceptLanguages`. + * @returns Array of LanguageCode. + */ + function getPreferredSystemLanguages(): Promise; + /** * 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. @@ -3540,12 +3490,14 @@ declare namespace browser.management { * `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, + * `admin`: The extension was installed by policy, * `other`: The extension was installed by other means. */ type ExtensionInstallType = | "development" | "normal" | "sideload" + | "admin" | "other"; /** Information about an installed extension. */ @@ -3684,7 +3636,7 @@ declare namespace browser.networkStatus { | "mobile"; /* networkStatus functions */ - /** Returns the $(ref:NetworkLinkInfo} of the current network connection. */ + /** Returns the `NetworkLinkInfo` of the current network connection. */ function getLinkInfo(): Promise; /* networkStatus events */ @@ -3727,7 +3679,7 @@ declare namespace browser.notifications { message: string; /** Alternate notification content with a lower-weight font. */ contextMessage?: string | undefined; - /** Priority ranges from -2 to 2\. -2 is lowest priority. 2 is highest. Zero is default. */ + /** Priority ranges from -2 to 2. -2 is lowest priority. 2 is highest. Zero is default. */ priority?: number | undefined; /** A timestamp associated with the notification, in milliseconds past the epoch. */ eventTime?: number | undefined; @@ -3761,7 +3713,7 @@ declare namespace browser.notifications { message?: string | undefined; /** Alternate notification content with a lower-weight font. */ contextMessage?: string | undefined; - /** Priority ranges from -2 to 2\. -2 is lowest priority. 2 is highest. Zero is default. */ + /** Priority ranges from -2 to 2. -2 is lowest priority. 2 is highest. Zero is default. */ priority?: number | undefined; /** A timestamp associated with the notification, in milliseconds past the epoch. */ eventTime?: number | undefined; @@ -3987,13 +3939,15 @@ declare namespace browser.pageAction { declare namespace browser.permissions { /* permissions types */ interface Permissions { - permissions?: _manifest.OptionalPermission[] | undefined; + permissions?: _manifest.OptionalPermission[] | _manifest.OptionalOnlyPermission[] | undefined; origins?: _manifest.MatchPattern[] | undefined; + data_collection?: _manifest.OptionalDataCollectionPermission[] | undefined; } interface AnyPermissions { - permissions?: _manifest.Permission[] | undefined; + permissions?: _manifest.Permission[] | _manifest.OptionalOnlyPermission[] | undefined; origins?: _manifest.MatchPattern[] | undefined; + data_collection?: _manifest.OptionalDataCollectionPermission[] | undefined; } /* permissions functions */ @@ -4233,7 +4187,7 @@ declare namespace browser.proxy { autoConfigUrl?: string | undefined; /** Do not prompt for authentication if password is saved. */ autoLogin?: boolean | undefined; - /** Proxy DNS when using SOCKS v5. */ + /** Proxy DNS when using SOCKS. DNS queries get leaked to the network when set to false. True by default for SOCKS v5. False by default for SOCKS v4. */ proxyDNS?: boolean | undefined; /** * If true (the default value), do not use newer TLS protocol features that might have interoperability problems on the Internet. This is intended only for use with critical infrastructure like the updates, and is only available to privileged addons. @@ -4310,6 +4264,54 @@ declare namespace browser.proxy { */ declare namespace browser.runtime { /* runtime types */ + /** + * A filter to match against existing extension context. Matching contexts must match all specified filters. + * + * Needs at least manifest version 3. + */ + interface ContextFilter { + contextIds?: string[] | undefined; + contextTypes?: ContextType[] | undefined; + documentIds?: string[] | undefined; + documentOrigins?: string[] | undefined; + documentUrls?: string[] | undefined; + frameIds?: number[] | undefined; + tabIds?: number[] | undefined; + windowIds?: number[] | undefined; + incognito?: boolean | undefined; + } + + /** The type of extension view. */ + type ContextType = + | "BACKGROUND" + | "POPUP" + | "SIDE_PANEL" + | "TAB"; + + interface ExtensionContext { + /** An unique identifier associated to this context. */ + contextId: string; + /** The type of the context. */ + contextType: ContextType; + /** + * An UUID for the document associated with this context, or undefined if it is not hosted in a document. + * @deprecated Unsupported on Firefox at this time. + */ + documentId?: string | undefined; + /** The origin of the document associated with this context, or undefined if it is not hosted in a document. */ + documentOrigin?: string | undefined; + /** The URL of the document associated with this context, or undefined if it is not hosted in a document. */ + documentUrl?: string | undefined; + /** Whether the context is associated with an private browsing context. */ + incognito: boolean; + /** The frame ID for this context, or -1 if it is not hosted in a frame. */ + frameId: number; + /** The tab ID for this context, or -1 if it is not hosted in a tab. */ + tabId: number; + /** The window ID for this context, or -1 if it is not hosted in a window. */ + windowId: number; + } + /** An object which allows two way communication with other pages. */ interface Port { name: string; @@ -4343,6 +4345,11 @@ declare namespace browser.runtime { * @deprecated Unsupported on Firefox at this time. */ tlsChannelId?: string | undefined; + + /** + * The worldId of the USER_SCRIPT world that sent the message. Only present on onUserScriptMessage and onUserScriptConnect (in port.sender) events. + */ + userScriptWorldId?: string | undefined; } /** The operating system the browser is running on. */ @@ -4410,6 +4417,26 @@ declare namespace browser.runtime { | "os_update" | "periodic"; + /** The performance warning event category, e.g. 'content_script'. */ + type OnPerformanceWarningCategory = "content_script"; + + /** The performance warning event severity. Will be 'high' for serious and user-visible issues. */ + type OnPerformanceWarningSeverity = + | "low" + | "medium" + | "high"; + + interface _OnPerformanceWarningDetails { + /** The performance warning event category, e.g. 'content_script'. */ + category: OnPerformanceWarningCategory; + /** The performance warning event severity, e.g. 'high'. */ + severity: OnPerformanceWarningSeverity; + /** The `tabs.Tab` that the performance warning relates to, if any. */ + tabId?: number | undefined; + /** An explanation of what the warning means, and hopefully how to address it. */ + description: string; + } + type PlatformNaclArch = | "arm" | "x86-32" @@ -4481,6 +4508,13 @@ declare namespace browser.runtime { */ function getBackgroundPage(): Promise; + /** + * Fetches information about active contexts associated with this extension. + * @param filter A filter to find matching context. + * @returns The matching contexts, if any. + */ + function getContexts(filter: ContextFilter): Promise; + /** * Open your Extension's options page, if possible. * @@ -4621,6 +4655,9 @@ declare namespace browser.runtime { /** 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 a USER_SCRIPT world registered through the userScripts API. */ + const onUserScriptConnect: WebExtEvent<(port: Port) => void>; + /** Fired when a connection is made from another extension. */ const onConnectExternal: WebExtEvent<(port: Port) => void>; @@ -4646,12 +4683,28 @@ declare namespace browser.runtime { (message: any, sender: MessageSender, sendResponse: (response?: any) => void) => boolean | Promise | void >; + /** + * Fired when a message is sent from a USER_SCRIPT world registered through the userScripts API. + * @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 onUserScriptMessage: WebExtEvent< + // eslint-disable-next-line @typescript-eslint/no-invalid-void-type + (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; + + /** + * Fired when a runtime performance issue is detected with the extension. Observe this event to be proactively notified of runtime performance problems with the extension. + */ + const onPerformanceWarning: WebExtEvent<(details: _OnPerformanceWarningDetails) => void>; } /** @@ -4731,9 +4784,11 @@ declare namespace browser.scripting { } /** - * The JavaScript world for a script to execute within. We currently only support the `'ISOLATED'` world. + * The JavaScript world for a script to execute within. `ISOLATED` is the default execution environment of content scripts, `MAIN` is the web page's execution environment. */ - type ExecutionWorld = "ISOLATED"; + type ExecutionWorld = + | "ISOLATED" + | "MAIN"; interface RegisteredContentScript { /** @@ -4752,10 +4807,16 @@ declare namespace browser.scripting { * Specifies which pages this content script will be injected into. Must be specified for `registerContentScripts()`. */ matches?: string[] | undefined; + /** + * If matchOriginAsFallback is true, then the code is also injected in about:, data:, blob: when their origin matches the pattern in 'matches', even if the actual document origin is opaque (due to the use of CSP sandbox or iframe sandbox). Match patterns in 'matches' must specify a wildcard path glob. By default it is `false`. + */ + matchOriginAsFallback?: boolean | undefined; /** * Specifies when JavaScript files are injected into the web page. The preferred and default value is `document_idle`. */ runAt?: extensionTypes.RunAt | undefined; + /** The JavaScript world for a script to execute within. Defaults to "ISOLATED". */ + world?: extensionTypes.ExecutionWorld | undefined; /** Specifies if this content script will persist into future sessions. Defaults to true. */ persistAcrossSessions?: boolean | undefined; /** @@ -4767,33 +4828,9 @@ declare namespace browser.scripting { /** The style origin for the injection. Defaults to `'AUTHOR'`. */ type _CSSInjectionOrigin = "USER" | "AUTHOR"; - interface _UpdateContentScriptsScripts { + interface _UpdateContentScriptsScripts extends RegisteredContentScript { /** Specifies if this content script will persist into future sessions. */ persistAcrossSessions?: boolean | undefined; - /** - * If specified true, it will inject into all frames, even if the frame is not the top-most frame in the tab. Each frame is checked independently for URL requirements; it will not inject into child frames if the URL requirements are not met. Defaults to false, meaning that only the top frame is matched. - */ - allFrames?: boolean | undefined; - /** Excludes pages that this content script would otherwise be injected into. */ - excludeMatches?: string[] | undefined; - /** The id of the content script, specified in the API call. */ - id: string; - /** - * The list of JavaScript files to be injected into matching pages. These are injected in the order they appear in this array. - */ - js?: _manifest.ExtensionURL[] | undefined; - /** - * Specifies which pages this content script will be injected into. Must be specified for `registerContentScripts()`. - */ - matches?: string[] | undefined; - /** - * Specifies when JavaScript files are injected into the web page. The preferred and default value is `document_idle`. - */ - runAt?: extensionTypes.RunAt | undefined; - /** - * The list of CSS files to be injected into matching pages. These are injected in the order they appear in this array. - */ - css?: _manifest.ExtensionURL[] | undefined; } /* scripting functions */ @@ -4863,10 +4900,12 @@ declare namespace browser.storage { get(keys?: null | 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. + * @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?: null | string | string[]): Promise; + /** Gets the keys of all items in storage. */ + getKeys(): 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. @@ -4888,7 +4927,7 @@ declare namespace browser.storage { onChanged: WebExtEvent<(changes: { [key: string]: StorageChange }) => void>; } - interface StorageAreaSync { + interface StorageAreaWithUsage { /** * 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. @@ -4896,9 +4935,11 @@ declare namespace browser.storage { get(keys?: null | 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. + * @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. */ getBytesInUse(keys?: null | string | string[]): Promise; + /** Gets the keys of all items in storage. */ + getKeys(): 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. @@ -4920,24 +4961,76 @@ declare namespace browser.storage { onChanged: WebExtEvent<(changes: { [key: string]: StorageChange }) => void>; } + interface _SyncStorageAreaWithUsage extends StorageAreaWithUsage { + /** + * The maximum total amount (in bytes) of data that can be stored in sync storage, as measured by the JSON stringification of every value plus every key's length. Updates that would cause this limit to be exceeded fail immediately and set `runtime.lastError`. + */ + QUOTA_BYTES: number; + /** + * The maximum size (in bytes) of each individual item in sync storage, as measured by the JSON stringification of its value plus its key length. Updates containing items larger than this limit will fail immediately and set `runtime.lastError`. + */ + QUOTA_BYTES_PER_ITEM: number; + /** + * The maximum number of items that can be stored in sync storage. Updates that would cause this limit to be exceeded will fail immediately and set `runtime.lastError`. + */ + MAX_ITEMS: number; + /** + * The maximum number of `set`, `remove`, or `clear` operations that can be performed each hour. This is 1 every 2 seconds, a lower ceiling than the short term higher writes-per-minute limit. + * + * Updates that would cause this limit to be exceeded fail immediately and set `runtime.lastError`. + */ + MAX_WRITE_OPERATIONS_PER_HOUR: number; + /** + * The maximum number of `set`, `remove`, or `clear` operations that can be performed each minute. This is 2 per second, providing higher throughput than writes-per-hour over a shorter period of time. + * + * Updates that would cause this limit to be exceeded fail immediately and set `runtime.lastError`. + */ + MAX_WRITE_OPERATIONS_PER_MINUTE: number; + /** + * @deprecated The storage.sync API no longer has a sustained write operation quota. + */ + MAX_SUSTAINED_WRITE_OPERATIONS_PER_MINUTE: number; + } + + interface _LocalStorageArea extends StorageArea { + /** + * The maximum amount (in bytes) of data that can be stored in local storage, as measured by the JSON stringification of every value plus every key's length. This value will be ignored if the extension has the `unlimitedStorage` permission. Updates that would cause this limit to be exceeded fail immediately and set `runtime.lastError`. + */ + QUOTA_BYTES: number; + } + + interface _ManagedStorageArea extends StorageArea { + /** + * The maximum size (in bytes) of the managed storage JSON manifest file. Files larger than this limit will fail to load. + */ + QUOTA_BYTES: number; + } + + interface _SessionStorageAreaWithUsage extends StorageAreaWithUsage { + /** + * The maximum amount of data (in bytes, currently at 10MB) that can be stored in session storage, as measured by the StructuredCloneHolder of every value plus every key's length. + */ + QUOTA_BYTES: number; + } + /* storage properties */ /** Items in the `sync` storage area are synced by the browser. */ - const sync: StorageAreaSync; + const sync: _SyncStorageAreaWithUsage; /** Items in the `local` storage area are local to each machine. */ - const local: StorageArea; + const local: _LocalStorageArea; /** * 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; + const managed: _ManagedStorageArea; /** * Items in the `session` storage area are kept in memory, and only until the either browser or extension is closed or reloaded. * * Not allowed in: Content scripts */ - const session: StorageArea; + const session: _SessionStorageAreaWithUsage; /* storage events */ /** @@ -5023,13 +5116,6 @@ declare namespace browser.telemetry { */ function submitPing(type: string, message: { [key: string]: any }, options: _SubmitPingOptions): Promise; - /** - * Submits a custom ping to the Telemetry back-end, with an encrypted payload. Requires a telemetry entry in the manifest to be used. - * @param message The data payload for the ping, which will be encrypted. - * @param options Options object. - */ - function submitEncryptedPing(message: { [key: string]: any }, options: _SubmitEncryptedPingOptions): Promise; - /** Checks if Telemetry upload is enabled. */ function canUpload(): Promise; @@ -5037,6 +5123,7 @@ declare namespace browser.telemetry { * 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. + * @deprecated `scalarAdd` is a no-op since Firefox 134 (see bug 1930196). */ function scalarAdd(name: string, value: number): Promise; @@ -5044,6 +5131,7 @@ declare namespace browser.telemetry { * 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 + * @deprecated `scalarSet` is a no-op since Firefox 134 (see bug 1930196). */ function scalarSet(name: string, value: string | boolean | number | { [key: string]: any }): Promise; @@ -5051,6 +5139,7 @@ declare namespace browser.telemetry { * 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. + * @deprecated `scalarSetMaximum` is a no-op since Firefox 134 (see bug 1930196). */ function scalarSetMaximum(name: string, value: number): Promise; @@ -5059,6 +5148,7 @@ declare namespace browser.telemetry { * @param name The scalar name * @param key The key name * @param value The numeric value to add to the scalar. Only unsigned integers supported. + * @deprecated `keyedScalarAdd` is a no-op since Firefox 134 (see bug 1930196). */ function keyedScalarAdd(name: string, key: string, value: number): Promise; @@ -5067,6 +5157,7 @@ declare namespace browser.telemetry { * @param name The scalar name. * @param key The key name. * @param value The value to set the scalar to. + * @deprecated `keyedScalarSet` is a no-op since Firefox 134 (see bug 1930196). */ function keyedScalarSet( name: string, @@ -5079,6 +5170,7 @@ declare namespace browser.telemetry { * @param name The scalar name. * @param key The key name. * @param value The numeric value to set the scalar to. Only unsigned integers supported. + * @deprecated `keyedScalarSetMaximum` is a no-op since Firefox 134 (see bug 1930196). */ function keyedScalarSetMaximum(name: string, key: string, value: number): Promise; @@ -5089,6 +5181,7 @@ declare namespace browser.telemetry { * @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. + * @deprecated `recordEvent` is a no-op since Firefox 132 (see bug 1894533). */ function recordEvent( category: string, @@ -5102,6 +5195,7 @@ declare namespace browser.telemetry { * 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. + * @deprecated `registerScalars` is a no-op since Firefox 134 (see bug 1930196). */ function registerScalars(category: string, data: { [key: string]: ScalarData }): Promise; @@ -5109,13 +5203,15 @@ declare namespace browser.telemetry { * 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. + * @deprecated `registerEvents` is a no-op since Firefox 132 (see bug 1894533). */ 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. + * Enable recording of events in a category. Events default to recording enabled. 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. + * @deprecated `setEventRecordingEnabled` is a no-op since Firefox 133 (see bug 1920562). */ function setEventRecordingEnabled(category: string, enabled: boolean): Promise; } @@ -5277,13 +5373,15 @@ declare namespace browser.types { /** * Manifest keys: `user_scripts`, `user_scripts` * - * Not supported on manifest versions above 2. - * * Not allowed in: Devtools pages */ declare namespace browser.userScripts { /* userScripts types */ - /** Details of a user script */ + /** + * Details of a user script. + * + * Not supported on manifest versions above 2. + */ interface UserScriptOptions { /** The list of JS files to inject */ js: extensionTypes.ExtensionFileOrCode[]; @@ -5307,10 +5405,98 @@ declare namespace browser.userScripts { cookieStoreId?: string[] | string | undefined; } - /** An object that represents a user script registered programmatically */ + /** + * An object that represents a user script registered programmatically. + * + * Not supported on manifest versions above 2. + */ + interface _LegacyRegisteredUserScript { + /** Unregister a user script registered programmatically. */ + unregister(): Promise; + } + + /** + * An object that represents a user script registered programmatically. + * + * Needs at least manifest version 3. + */ interface RegisteredUserScript { - /** Unregister a user script registered programmatically */ - unregister(): Promise; + /** + * The ID of the user script specified in the API call. This property must not start with a '_' as it's reserved as a prefix for generated script IDs. + */ + id: 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 | undefined; + /** The list of ScriptSource objects defining sources of scripts to be injected into matching pages. */ + js: ScriptSource[]; + /** At least one of matches or includeGlobs should be non-empty. The script runs in documents whose URL match either pattern. */ + matches?: _manifest.MatchPattern[] | undefined; + excludeMatches?: _manifest.MatchPattern[] | undefined; + /** At least one of matches or includeGlobs should be non-empty. The script runs in documents whose URL match either pattern. */ + includeGlobs?: string[] | undefined; + excludeGlobs?: string[] | undefined; + /** The soonest that the JavaScript will be injected into the tab. Defaults to "document_idle". */ + runAt?: extensionTypes.RunAt | undefined; + /** The JavaScript script for a script to execute within. Defaults to "USER_SCRIPT". */ + world?: ExecutionWorld | undefined; + /** If specified, specifies a specific user script world ID to execute in. Only valid if `world` is omitted or is `USER_SCRIPT`. If `worldId` is omitted, the script will execute in the default user script world (""). Values with leading underscores (`_`) are reserved. The maximum length is 256. */ + worldId?: string | undefined; + } + + interface _UpdateRegisteredUserScript extends Omit { + js?: ScriptSource[] | undefined; + } + + /** + * The JavaScript world for a script to execute within. `USER_SCRIPT` is the default execution environment of user scripts, `MAIN` is the web page's execution environment. + * + * Needs at least manifest version 3. + */ + type ExecutionWorld = + | "MAIN" + | "USER_SCRIPT"; + + /** + * Optional filter to use with getScripts() and unregister(). + * + * Needs at least manifest version 3. + */ + interface UserScriptFilter { + ids?: string[] | undefined; + } + + /** + * Object with file xor code property. Equivalent to the ExtensionFileOrCode, except the file remains a relative URL. + * + * Needs at least manifest version 3. + */ + type ScriptSource = { + /** The path of the JavaScript file to inject relative to the extension's root directory. */ + file: string; + } | { + code: string; + }; + + /** + * The configuration of a USER_SCRIPT world. + * + * Needs at least manifest version 3. + */ + interface WorldProperties { + /** + * The identifier of the world. Values with leading underscores (`_`) are reserved. The maximum length is 256. Defaults to the default USER_SCRIPT world (""). + */ + worldId?: string | undefined; + /** + * The world's Content Security Policy. Defaults to the CSP of regular content scripts, which prohibits dynamic code execution such as eval. + */ + csp?: string | undefined; + /** + * Whether the runtime.sendMessage and runtime.connect methods are exposed. Defaults to not exposing these messaging APIs. + */ + messaging?: boolean | undefined; } interface _OnBeforeScriptUserScript { @@ -5332,13 +5518,75 @@ declare namespace browser.userScripts { /* userScripts functions */ /** - * Register a user script programmatically given its `userScripts.UserScriptOptions`, and resolves to a `userScripts.RegisteredUserScript` instance + * Register a user script programmatically given its `userScripts.UserScriptOptions`, and resolves to an object with the unregister() function. + * @param userScriptOptions An object that represents a user script registered programmatically. + * + * Not supported on manifest versions above 2. + */ + function register(userScriptOptions: UserScriptOptions): Promise<_LegacyRegisteredUserScript>; + + /** + * Registers one or more user scripts for this extension. + * @param scripts List of user scripts to be registered. + * + * Needs at least manifest version 3. + */ + function register(scripts: RegisteredUserScript[]): Promise; + + /** + * Updates one or more user scripts for this extension. + * @param scripts List of user scripts to be updated. + * + * Needs at least manifest version 3. + */ + function update(scripts: _UpdateRegisteredUserScript[]): Promise; + + /** + * Unregisters all dynamically-registered user scripts for this extension. + * @param filter If specified, this method unregisters only the user scripts that match it. + * + * Needs at least manifest version 3. + */ + function unregister(filter?: UserScriptFilter): Promise; + + /** + * Returns all dynamically-registered user scripts for this extension. + * @param filter If specified, this method returns only the user scripts that match it. + * @returns List of registered user scripts. + * + * Needs at least manifest version 3. */ - function register(userScriptOptions: UserScriptOptions): Promise; + function getScripts(filter?: UserScriptFilter): Promise; + + /** + * Configures the environment for scripts running in a USER_SCRIPT world. + * @param properties The desired configuration for a USER_SCRIPT world. + * + * Needs at least manifest version 3. + */ + function configureWorld(properties: WorldProperties): Promise; + + /** + * Resets the configuration for a given world. That world will fall back to the default world's configuration. + * @param worldId The ID of the USER_SCRIPT world to reset. If omitted or empty, resets the default world's configuration. + * + * Needs at least manifest version 3. + */ + function resetWorldConfiguration(worldId?: string): Promise; + + /** + * Returns all registered USER_SCRIPT world configurations. + * @returns All configurations registered with configureWorld(). + * + * Needs at least manifest version 3. + */ + function getWorldConfigurations(): Promise; /* userScripts events */ /** - * Event called when a new userScript global has been created + * Event called when a new userScript global has been created. + * + * Not supported on manifest versions above 2. * * Allowed in: Content scripts only */ @@ -5656,7 +5904,7 @@ declare namespace browser.webNavigation { /* webNavigation functions */ /** - * Retrieves information about the given frame. A frame refers to an