diff --git a/packages/browser/package.json b/packages/browser/package.json index f247fe8e..bdaa8f2d 100644 --- a/packages/browser/package.json +++ b/packages/browser/package.json @@ -1,7 +1,7 @@ { "name": "@wxt-dev/browser", "description": "Provides a cross-browser API for using extension APIs and types based on @types/chrome", - "version": "0.1.4", + "version": "0.1.32", "type": "module", "main": "src/index.mjs", "types": "src/index.d.ts", @@ -23,12 +23,12 @@ "src" ], "devDependencies": { - "@types/chrome": "0.1.6", + "@types/chrome": "0.1.32", "fs-extra": "^11.3.1", "nano-spawn": "^1.0.2", - "tsx": "4.20.5", + "tsx": "4.19.4", "typescript": "^5.9.2", - "vitest": "^3.2.4" + "vitest": "^3.1.2" }, "dependencies": { "@types/filesystem": "*", diff --git a/packages/browser/src/gen/index.d.ts b/packages/browser/src/gen/index.d.ts index f6c16334..456894b6 100644 --- a/packages/browser/src/gen/index.d.ts +++ b/packages/browser/src/gen/index.d.ts @@ -155,7 +155,7 @@ export namespace Browser { export namespace action { export interface BadgeColorDetails { /** An array of four integers in the range [0,255] that make up the RGBA color of the badge. For example, opaque red is `[255, 0, 0, 255]`. Can also be a string with a CSS value, with opaque red being `#FF0000` or `#F00`. */ - color: string | ColorArray; + color: string | extensionTypes.ColorArray; /** Limits the change to when a particular tab is selected. Automatically resets when the tab is closed. */ tabId?: number | undefined; } @@ -167,8 +167,6 @@ export namespace Browser { tabId?: number | undefined; } - export type ColorArray = [number, number, number, number]; - export interface TitleDetails { /** The string the action should display when moused over. */ title: string; @@ -243,11 +241,14 @@ export namespace Browser { * * Can return its result via Promise. */ - export function getBadgeBackgroundColor(details: TabDetails): Promise; - export function getBadgeBackgroundColor(details: TabDetails, callback: (result: ColorArray) => void): void; + export function getBadgeBackgroundColor(details: TabDetails): Promise; + export function getBadgeBackgroundColor( + details: TabDetails, + callback: (result: extensionTypes.ColorArray) => void, + ): void; /** - * Gets the badge text of the action. If no tab is specified, the non-tab-specific badge text is returned. If {@link declarativeNetRequest.ExtensionActionOptions.displayActionCountAsBadgeText displayActionCountAsBadgeText} is enabled, a placeholder text will be returned unless the {@link runtime.ManifestPermissions declarativeNetRequestFeedback} permission is present or tab-specific badge text was provided. + * Gets the badge text of the action. If no tab is specified, the non-tab-specific badge text is returned. If {@link declarativeNetRequest.ExtensionActionOptions.displayActionCountAsBadgeText displayActionCountAsBadgeText} is enabled, a placeholder text will be returned unless the {@link runtime.ManifestPermission declarativeNetRequestFeedback} permission is present or tab-specific badge text was provided. * * Can return its result via Promise. */ @@ -260,8 +261,11 @@ export namespace Browser { * Can return its result via Promise. * @since Chrome 110 */ - export function getBadgeTextColor(details: TabDetails): Promise; - export function getBadgeTextColor(details: TabDetails, callback: (result: ColorArray) => void): void; + export function getBadgeTextColor(details: TabDetails): Promise; + export function getBadgeTextColor( + details: TabDetails, + callback: (result: extensionTypes.ColorArray) => void, + ): void; /** * Gets the html document set as the popup for this action. @@ -379,120 +383,76 @@ export namespace Browser { */ export namespace alarms { export interface AlarmCreateInfo { - /** Optional. Length of time in minutes after which the onAlarm event should fire. */ + /** Length of time in minutes after which the {@link onAlarm} event should fire. */ delayInMinutes?: number | undefined; - /** Optional. If set, the onAlarm event should fire every periodInMinutes minutes after the initial event specified by when or delayInMinutes. If not set, the alarm will only fire once. */ + /** If set, the onAlarm event should fire every `periodInMinutes` minutes after the initial event specified by `when` or `delayInMinutes`. If not set, the alarm will only fire once. */ periodInMinutes?: number | undefined; - /** Optional. Time at which the alarm should fire, in milliseconds past the epoch (e.g. Date.now() + n). */ + /** Time at which the alarm should fire, in milliseconds past the epoch (e.g. `Date.now() + n`). */ when?: number | undefined; } export interface Alarm { - /** Optional. If not null, the alarm is a repeating alarm and will fire again in periodInMinutes minutes. */ - periodInMinutes?: number | undefined; - /** Time at which this alarm was scheduled to fire, in milliseconds past the epoch (e.g. Date.now() + n). For performance reasons, the alarm may have been delayed an arbitrary amount beyond this. */ + /** If not null, the alarm is a repeating alarm and will fire again in `periodInMinutes` minutes. */ + periodInMinutes?: number; + /** Time at which this alarm was scheduled to fire, in milliseconds past the epoch (e.g. `Date.now() + n`). For performance reasons, the alarm may have been delayed an arbitrary amount beyond this. */ scheduledTime: number; /** Name of this alarm. */ name: string; } - export interface AlarmEvent extends Browser.events.Event<(alarm: Alarm) => void> {} - /** - * Creates an alarm. Near the time(s) specified by alarmInfo, 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. - * In order to reduce the load on the user's machine, Chrome limits alarms to at most once every 1 minute but may delay them an arbitrary amount more. That is, setting delayInMinutes or periodInMinutes to less than 1 will not be honored and will cause a warning. when can be set to less than 1 minute after "now" without warning but won't actually cause the alarm to fire for at least 1 minute. + * Creates an alarm. Near the time(s) specified by `alarmInfo`, the {@link 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. + * + * In order to reduce the load on the user's machine, Chrome limits alarms to at most once every 30 seconds but may delay them an arbitrary amount more. That is, setting `delayInMinutes` or `periodInMinutes` to less than `0.5` will not be honored and will cause a warning. `when` can be set to less than 30 seconds after "now" without warning but won't actually cause the alarm to fire for at least 30 seconds. + * * To help you debug your app or extension, when you've loaded it unpacked, there's no limit to how often the alarm can fire. - * @param alarmInfo Describes when the alarm should fire. The initial time must be specified by either when or delayInMinutes (but not both). If periodInMinutes is set, the alarm will repeat every periodInMinutes minutes after the initial event. If neither when or delayInMinutes is set for a repeating alarm, periodInMinutes is used as the default for delayInMinutes. - * @return The `create` method provides its result via callback or returned as a `Promise` (MV3 only). + * @param name Optional name to identify this alarm. Defaults to the empty string. + * @param alarmInfo Describes when the alarm should fire. The initial time must be specified by either `when` or `delayInMinutes` (but not both). If `periodInMinutes` is set, the alarm will repeat every `periodInMinutes` minutes after the initial event. If neither `when` or `delayInMinutes` is set for a repeating alarm, `periodInMinutes` is used as the default for `delayInMinutes`. + * + * Can return its result via Promise in Manifest V3 or later since Chrome 111. */ export function create(alarmInfo: AlarmCreateInfo): Promise; - /** - * Creates an alarm. Near the time(s) specified by alarmInfo, 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. - * In order to reduce the load on the user's machine, Chrome limits alarms to at most once every 1 minute but may delay them an arbitrary amount more. That is, setting delayInMinutes or periodInMinutes to less than 1 will not be honored and will cause a warning. when can be set to less than 1 minute after "now" without warning but won't actually cause the alarm to fire for at least 1 minute. - * To help you debug your app or extension, when you've loaded it unpacked, there's no limit to how often the alarm can fire. - * @param name Optional name to identify this alarm. Defaults to the empty string. - * @param alarmInfo Describes when the alarm should fire. The initial time must be specified by either when or delayInMinutes (but not both). If periodInMinutes is set, the alarm will repeat every periodInMinutes minutes after the initial event. If neither when or delayInMinutes is set for a repeating alarm, periodInMinutes is used as the default for delayInMinutes. - * @return The `create` method provides its result via callback or returned as a `Promise` (MV3 only). - */ - export function create(name: string, alarmInfo: AlarmCreateInfo): Promise; - /** - * Creates an alarm. Near the time(s) specified by alarmInfo, 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. - * In order to reduce the load on the user's machine, Chrome limits alarms to at most once every 1 minute but may delay them an arbitrary amount more. That is, setting delayInMinutes or periodInMinutes to less than 1 will not be honored and will cause a warning. when can be set to less than 1 minute after "now" without warning but won't actually cause the alarm to fire for at least 1 minute. - * To help you debug your app or extension, when you've loaded it unpacked, there's no limit to how often the alarm can fire. - * @param alarmInfo Describes when the alarm should fire. The initial time must be specified by either when or delayInMinutes (but not both). If periodInMinutes is set, the alarm will repeat every periodInMinutes minutes after the initial event. If neither when or delayInMinutes is set for a repeating alarm, periodInMinutes is used as the default for delayInMinutes. - */ + export function create(name: string | undefined, alarmInfo: AlarmCreateInfo): Promise; export function create(alarmInfo: AlarmCreateInfo, callback: () => void): void; - /** - * Creates an alarm. Near the time(s) specified by alarmInfo, 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. - * In order to reduce the load on the user's machine, Chrome limits alarms to at most once every 1 minute but may delay them an arbitrary amount more. That is, setting delayInMinutes or periodInMinutes to less than 1 will not be honored and will cause a warning. when can be set to less than 1 minute after "now" without warning but won't actually cause the alarm to fire for at least 1 minute. - * To help you debug your app or extension, when you've loaded it unpacked, there's no limit to how often the alarm can fire. - * @param name Optional name to identify this alarm. Defaults to the empty string. - * @param alarmInfo Describes when the alarm should fire. The initial time must be specified by either when or delayInMinutes (but not both). If periodInMinutes is set, the alarm will repeat every periodInMinutes minutes after the initial event. If neither when or delayInMinutes is set for a repeating alarm, periodInMinutes is used as the default for delayInMinutes. - */ - export function create(name: string, alarmInfo: AlarmCreateInfo, callback: () => void): void; + export function create(name: string | undefined, alarmInfo: AlarmCreateInfo, callback: () => void): void; + /** * Gets an array of all the alarms. - */ - export function getAll(callback: (alarms: Alarm[]) => void): void; - /** - * Gets an array of all the alarms. - * @return The `getAll` method provides its result via callback or returned as a `Promise` (MV3 only). + * + * Can return its result via Promise in Manifest V3 or later since Chrome 91. */ export function getAll(): Promise; + export function getAll(callback: (alarms: Alarm[]) => void): void; + /** * Clears all alarms. - * function(boolean wasCleared) {...}; - * @return The `clearAll` method provides its result via callback or returned as a `Promise` (MV3 only). + * + * Can return its result via Promise in Manifest V3 or later since Chrome 91. */ export function clearAll(): Promise; - /** - * Clears all alarms. - */ export function clearAll(callback: (wasCleared: boolean) => void): void; + /** * Clears the alarm with the given name. - * @param name The name of the alarm to clear. Defaults to the empty string. - * @return The `clear` method provides its result via callback or returned as a `Promise` (MV3 only). + * + * Can return its result via Promise in Manifest V3 or later since Chrome 91. */ export function clear(name?: string): Promise; - /** - * Clears the alarm with the given name. - * @param name The name of the alarm to clear. Defaults to the empty string. - */ export function clear(callback: (wasCleared: boolean) => void): void; - export function clear(name: string, callback: (wasCleared: boolean) => void): void; - /** - * Clears the alarm without a name. - */ - export function clear(callback: (wasCleared: boolean) => void): void; - /** - * Clears the alarm without a name. - * @return The `clear` method provides its result via callback or returned as a `Promise` (MV3 only). - */ - export function clear(): Promise; + export function clear(name: string | undefined, callback: (wasCleared: boolean) => void): void; + /** * Retrieves details about the specified alarm. + * @param name The name of the alarm to get. Defaults to the empty string. + * + * Can return its result via Promise in Manifest V3 or later since Chrome 91. */ + export function get(name?: string): Promise; export function get(callback: (alarm?: Alarm) => void): void; - /** - * Retrieves details about the specified alarm. - * @return The `get` method provides its result via callback or returned as a `Promise` (MV3 only). - */ - export function get(): Promise; - /** - * Retrieves details about the specified alarm. - * @param name The name of the alarm to get. Defaults to the empty string. - */ - export function get(name: string, callback: (alarm?: Alarm) => void): void; - /** - * Retrieves details about the specified alarm. - * @param name The name of the alarm to get. Defaults to the empty string. - * @return The `get` method provides its result via callback or returned as a `Promise` (MV3 only). - */ - export function get(name: string): Promise; + export function get(name: string | undefined, callback: (alarm?: Alarm) => void): void; /** Fired when an alarm has elapsed. Useful for event pages. */ - export var onAlarm: AlarmEvent; + export const onAlarm: events.Event<(alarm: Alarm) => void>; } //////////////////// @@ -909,173 +869,120 @@ export namespace Browser { */ export namespace browserAction { export interface BadgeBackgroundColorDetails { - /** An array of four integers in the range [0,255] that make up the RGBA color of the badge. For example, opaque red is [255, 0, 0, 255]. Can also be a string with a CSS value, with opaque red being #FF0000 or #F00. */ - color: string | ColorArray; - /** Optional. Limits the change to when a particular tab is selected. Automatically resets when the tab is closed. */ - tabId?: number | undefined; + /** An array of four integers in the range 0-255 that make up the RGBA color of the badge. Can also be a string with a CSS hex color value; for example, `#FF0000` or `#F00` (red). Renders colors at full opacity. */ + color: string | extensionTypes.ColorArray; + /** Limits the change to when a particular tab is selected. Automatically resets when the tab is closed. */ + tabId?: number | null | undefined; } export interface BadgeTextDetails { - /** Any number of characters can be passed, but only about four can fit in the space. */ + /** Any number of characters can be passed, but only about four can fit into the space. If an empty string (`''`) is passed, the badge text is cleared. If `tabId` is specified and `text` is null, the text for the specified tab is cleared and defaults to the global badge text. */ text?: string | null | undefined; - /** Optional. Limits the change to when a particular tab is selected. Automatically resets when the tab is closed. */ - tabId?: number | undefined; + /** Limits the change to when a particular tab is selected. Automatically resets when the tab is closed. */ + tabId?: number | null | undefined; } - export type ColorArray = [number, number, number, number]; - export interface TitleDetails { /** The string the browser action should display when moused over. */ title: string; /** Optional. Limits the change to when a particular tab is selected. Automatically resets when the tab is closed. */ - tabId?: number | null; + tabId?: number | null | undefined; } export interface TabDetails { - /** Optional. Specify the tab to get the information. If no tab is specified, the non-tab-specific information is returned. */ - tabId?: number | null; + /** The ID of the tab to query state for. If no tab is specified, the non-tab-specific state is returned. */ + tabId?: number | null | undefined; } - export interface TabIconDetails { - /** Optional. Either a relative image path or a dictionary {size -> relative image path} pointing to 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.path = foo' is equivalent to 'details.imageData = {'19': foo}' */ - path?: string | { [index: string]: string } | undefined; - /** Optional. Limits the change to when a particular tab is selected. Automatically resets when the tab is closed. */ - tabId?: number | undefined; - /** Optional. 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}' */ - imageData?: ImageData | { [index: number]: ImageData } | undefined; - } + export type TabIconDetails = + & { + /** Limits the change to when a particular tab is selected. Automatically resets when the tab is closed. */ + tabId?: number | null | undefined; + } + & ( + | { + /** Either an ImageData object or a dictionary {size -> ImageData} representing an icon to be set. If the icon is specified as a dictionary, the image used is chosen depending on the screen's pixel density. If the number of image pixels that fit into one screen space unit equals `scale`, then an image with size `scale` \* n is selected, where _n_ is the size of the icon in the UI. At least one image must be specified. Note that 'details.imageData = foo' is equivalent to 'details.imageData = {'16': foo}' */ + imageData: ImageData | { [index: number]: ImageData }; + /** Either a relative image path or a dictionary {size -> relative image path} pointing to an icon to be set. If the icon is specified as a dictionary, the image used is chosen depending on the screen's pixel density. If the number of image pixels that fit into one screen space unit equals `scale`, then an image with size `scale` \* n is selected, where _n_ is the size of the icon in the UI. At least one image must be specified. Note that 'details.path = foo' is equivalent to 'details.path = {'16': foo}' */ + path?: string | { [index: string]: string } | undefined; + } + | { + /** Either an ImageData object or a dictionary {size -> ImageData} representing an icon to be set. If the icon is specified as a dictionary, the image used is chosen depending on the screen's pixel density. If the number of image pixels that fit into one screen space unit equals `scale`, then an image with size `scale` \* n is selected, where _n_ is the size of the icon in the UI. At least one image must be specified. Note that 'details.imageData = foo' is equivalent to 'details.imageData = {'16': foo}' */ + imageData?: ImageData | { [index: number]: ImageData } | undefined; + /** Either a relative image path or a dictionary {size -> relative image path} pointing to an icon to be set. If the icon is specified as a dictionary, the image used is chosen depending on the screen's pixel density. If the number of image pixels that fit into one screen space unit equals `scale`, then an image with size `scale` \* n is selected, where _n_ is the size of the icon in the UI. At least one image must be specified. Note that 'details.path = foo' is equivalent to 'details.path = {'16': foo}' */ + path: string | { [index: string]: string }; + } + ); export interface PopupDetails { - /** Optional. Limits the change to when a particular tab is selected. Automatically resets when the tab is closed. */ - tabId?: number | null; - /** The html file to show in a popup. If set to the empty string (''), no popup is shown. */ + /** Limits the change to when a particular tab is selected. Automatically resets when the tab is closed. */ + tabId?: number | null | undefined; + /** The relative path to the HTML file to show in a popup. If set to the empty string (`''`), no popup is shown.*/ popup: string; } - export interface BrowserClickedEvent extends Browser.events.Event<(tab: Browser.tabs.Tab) => void> {} - /** - * @since Chrome 22 - * Enables the browser action for a tab. By default, browser actions are enabled. - * @param tabId The id of the tab for which you want to modify the browser action. - * @return The `enable` method provides its result via callback or returned as a `Promise` (MV3 only). It has no parameters. - */ - export function enable(tabId?: number | null): Promise; - /** - * @since Chrome 22 - * Enables the browser action for a tab. By default, browser actions are enabled. - * @param tabId The id of the tab for which you want to modify the browser action. - * @param callback Supported since Chrome 67 + * Enables the browser action for a tab. Defaults to enabled. + * @param tabId The ID of the tab for which to modify the browser action. + * @param callback Since Chrome 67 */ export function enable(callback?: () => void): void; export function enable(tabId: number | null | undefined, callback?: () => void): void; + /** * Sets the background color for the badge. - * @return The `setBadgeBackgroundColor` method provides its result via callback or returned as a `Promise` (MV3 only). It has no parameters. - */ - export function setBadgeBackgroundColor(details: BadgeBackgroundColorDetails): Promise; - /** - * Sets the background color for the badge. - * @param callback Supported since Chrome 67 + * @param callback Since Chrome 67 */ export function setBadgeBackgroundColor(details: BadgeBackgroundColorDetails, callback?: () => void): void; + /** * Sets the badge text for the browser action. The badge is displayed on top of the icon. - * @return The `setBadgeText` method provides its result via callback or returned as a `Promise` (MV3 only). It has no parameters. + * @param callback Since Chrome 67 */ - export function setBadgeText(details: BadgeTextDetails): Promise; + export function setBadgeText(details: BadgeTextDetails, callback?: () => void): void; + /** - * Sets the badge text for the browser action. The badge is displayed on top of the icon. - * @param callback Supported since Chrome 67 - */ - export function setBadgeText(details: BadgeTextDetails, callback: () => void): void; - /** - * Sets the title of the browser action. This shows up in the tooltip. - * @return The `setTitle` method provides its result via callback or returned as a `Promise` (MV3 only). It has no parameters. - */ - export function setTitle(details: TitleDetails): Promise; - /** - * Sets the title of the browser action. This shows up in the tooltip. - * @param callback Supported since Chrome 67 - */ - export function setTitle(details: TitleDetails, callback: () => void): void; - /** - * @since Chrome 19 - * Gets the badge text of the browser action. If no tab is specified, the non-tab-specific badge text is returned. - * @param callback Supported since Chrome 67 + * Sets the title of the browser action. This title appears in the tooltip. + * @param callback Since Chrome 67 */ + export function setTitle(details: TitleDetails, callback?: () => void): void; + + /** Gets the badge text of the browser action. If no tab is specified, the non-tab-specific badge text is returned. */ export function getBadgeText(details: TabDetails, callback: (result: string) => void): void; + /** - * @since Chrome 19 - * Gets the badge text of the browser action. If no tab is specified, the non-tab-specific badge text is returned. - * @return The `getBadgeText` method provides its result via callback or returned as a `Promise` (MV3 only). - */ - export function getBadgeText(details: TabDetails): Promise; - /** - * Sets the html document to be opened as a popup when the user clicks on the browser action's icon. - * @return The `setPopup` method provides its result via callback or returned as a `Promise` (MV3 only). It has no parameters. - */ - export function setPopup(details: PopupDetails): Promise; - /** - * Sets the html document to be opened as a popup when the user clicks on the browser action's icon. - * @param callback Supported since Chrome 67 + * Sets the HTML document to be opened as a popup when the user clicks the browser action icon. + * @param callback Since Chrome 67 */ export function setPopup(details: PopupDetails, callback?: () => void): void; + /** - * @since Chrome 22 * Disables the browser action for a tab. - * @param tabId The id of the tab for which you want to modify the browser action. - * @return The `disable` method provides its result via callback or returned as a `Promise` (MV3 only). It has no parameters. - */ - export function disable(tabId?: number | null): Promise; - /** - * @since Chrome 22 - * Disables the browser action for a tab. - * @param tabId The id of the tab for which you want to modify the browser action. - * @param callback Supported since Chrome 67 - */ - export function disable(callback: () => void): void; - export function disable(tabId?: number | null, callback?: () => void): void; - /** - * @since Chrome 19 - * Gets the title of the browser action. + * @param tabId The ID of the tab for which to modify the browser action. + * @param callback since Chrome 67 */ + export function disable(callback?: () => void): void; + export function disable(tabId: number | null | undefined, callback?: () => void): void; + + /** Gets the title of the browser action. */ export function getTitle(details: TabDetails, callback: (result: string) => void): void; - /** - * @since Chrome 19 - * Gets the title of the browser action. - * @return The `getTitle` method provides its result via callback or returned as a `Promise` (MV3 only). - */ - export function getTitle(details: TabDetails): Promise; - /** - * @since Chrome 19 - * Gets the background color of the browser action. - */ - export function getBadgeBackgroundColor(details: TabDetails, callback: (result: ColorArray) => void): void; - /** - * @since Chrome 19 - * Gets the background color of the browser action. - * @return The `getBadgeBackgroundColor` method provides its result via callback or returned as a `Promise` (MV3 only). - */ - export function getBadgeBackgroundColor(details: TabDetails): Promise; - /** - * @since Chrome 19 - * Gets the html document set as the popup for this browser action. - */ + + /** Gets the background color of the browser action. */ + export function getBadgeBackgroundColor( + details: TabDetails, + callback: (result: extensionTypes.ColorArray) => void, + ): void; + + /** Gets the HTML document that is set as the popup for this browser action. */ export function getPopup(details: TabDetails, callback: (result: string) => void): void; + /** - * @since Chrome 19 - * Gets the html document set as the popup for this browser action. - * @return The `getPopup` method provides its result via callback or returned as a `Promise` (MV3 only). - */ - export function getPopup(details: TabDetails): Promise; - /** - * Sets the icon for the browser action. The icon can be specified either as the path to an image file or as the pixel data from a canvas element, or as dictionary of either one of those. Either the path or the imageData property must be specified. + * Sets the icon for the browser action. The icon can be specified as the path to an image file, as the pixel data from a canvas element, or as a dictionary of one of those. Either the `path` or the `imageData` property must be specified. */ export function setIcon(details: TabIconDetails, callback?: () => void): void; - /** Fired when a browser action icon is clicked. This event will not fire if the browser action has a popup. */ - export var onClicked: BrowserClickedEvent; + /** Fired when a browser action icon is clicked. Does not fire if the browser action has a popup. */ + export const onClicked: events.Event<(tab: Browser.tabs.Tab) => void>; } //////////////////// @@ -1122,7 +1029,10 @@ export namespace Browser { indexedDB?: boolean | undefined; /** The browser's cookies. */ cookies?: boolean | undefined; - /** Stored passwords. */ + /** + * Stored passwords. + * @deprecated Support for password deletion through extensions has been removed. This data type will be ignored. + */ passwords?: boolean | undefined; /** * Server-bound certificates. @@ -1217,6 +1127,7 @@ export namespace Browser { * Clears the browser's stored passwords. * * Can return its result via Promise in Manifest V3 or later since Chrome 96. + * @deprecated Support for password deletion through extensions has been removed. This function has no effect. */ export function removePasswords(options: RemovalOptions): Promise; export function removePasswords(options: RemovalOptions, callback: () => void): void; @@ -1751,6 +1662,12 @@ export namespace Browser { INCOGNITO_SESSION_ONLY = "incognito_session_only", } + /** @since Chrome 141 */ + export enum SoundContentSetting { + ALLOW = "allow", + BLOCK = "block", + } + /** * Whether to allow sites to download multiple files automatically. One of * @@ -2452,45 +2369,70 @@ export namespace Browser { * Permissions: "declarativeContent" */ export namespace declarativeContent { - export class PageStateMatcherProperties { - /** Optional. Filters URLs for various criteria. See event filtering. All criteria are case sensitive. */ + interface PageStateMatcherProperties { + /** Matches if the conditions of the `UrlFilter` are fulfilled for the top-level URL of the page. */ pageUrl?: events.UrlFilter | undefined; - /** Optional. Matches if all of the CSS selectors in the array match displayed elements in a frame with the same origin as the page's main frame. All selectors in this array must be compound selectors to speed up matching. Note that listing hundreds of CSS selectors or CSS selectors that match hundreds of times per page can still slow down web sites. */ + /** Matches if all of the CSS selectors in the array match displayed elements in a frame with the same origin as the page's main frame. All selectors in this array must be compound selectors to speed up matching. Note: Listing hundreds of CSS selectors or listing CSS selectors that match hundreds of times per page can slow down web sites. */ css?: string[] | undefined; /** - * Optional. - * @since Chrome 45 * Matches if the bookmarked state of the page is equal to the specified value. Requires the bookmarks permission. + * @since Chrome 45 */ isBookmarked?: boolean | undefined; } - /** Matches the state of a web page by various criteria. */ + /** Matches the state of a web page based on various criteria. */ export class PageStateMatcher { - constructor(options: PageStateMatcherProperties); + constructor(arg: PageStateMatcherProperties); + } + + export interface RequestContentScriptProperties { + /** Whether the content script runs in all frames of the matching page, or in only the top frame. Default is `false`. */ + allFrames?: boolean | undefined; + + /** Names of CSS files to be injected as a part of the content script. */ + css?: string[] | undefined; + + /** Names of JavaScript files to be injected as a part of the content script. */ + js?: string[] | undefined; + + /** Whether to insert the content script on `about:blank` and `about:srcdoc`. Default is `false`. */ + matchAboutBlank?: boolean | undefined; + } + + /** Declarative event action that injects a content script. */ + export class RequestContentScript { + constructor(arg: RequestContentScriptProperties); } /** - * Declarative event action that enables the extension's action while the corresponding conditions are met. - * Manifest v3. + * A declarative event action that sets the extension's toolbar {@link action} to an enabled state while the corresponding conditions are met. This action can be used without host permissions. If the extension has the `activeTab` permission, clicking the page action grants access to the active tab. + * + * On pages where the conditions are not met the extension's toolbar action will be grey-scale, and clicking it will open the context menu, instead of triggering the action. + * @since MV3 */ export class ShowAction {} /** - * Declarative event action that shows the extension's page action while the corresponding conditions are met. - * Manifest v2. + * A declarative event action that sets the extension's {@link pageAction} to an enabled state while the corresponding conditions are met. This action can be used without host permissions, but the extension must have a page action. If the extension has the `activeTab` permission, clicking the page action grants access to the active tab. + * + * On pages where the conditions are not met the extension's toolbar action will be grey-scale, and clicking it will open the context menu, instead of triggering the action. + * + * MV2 only */ export class ShowPageAction {} - /** Declarative event action that changes the icon of the page action while the corresponding conditions are met. */ + /** + * Declarative event action that sets the n-dip square icon for the extension's {@link pageAction} or {@link browserAction} while the corresponding conditions are met. This action can be used without host permissions, but the extension must have a page or browser action. + * + * Exactly one of `imageData` or `path` must be specified. Both are dictionaries mapping a number of pixels to an image representation. The image representation in `imageData` is an `ImageData` object; for example, from a `canvas` element, while the image representation in `path` is the path to an image file relative to the extension's manifest. If `scale` screen pixels fit into a device-independent pixel, the `scale * n` icon is used. If that scale is missing, another image is resized to the required size. + */ export class SetIcon { constructor(options?: { imageData?: ImageData | { [size: string]: ImageData } | undefined }); } - /** Provides the Declarative Event API consisting of addRules, removeRules, and getRules. */ - export interface PageChangedEvent extends Browser.events.Event<() => void> {} - - export var onPageChanged: PageChangedEvent; + /** Provides the Declarative Event API consisting of {@link events.Event.addRules addRules}, {@link events.Event.removeRules removeRules}, and {@link events.Event.getRules getRules}. */ + export const onPageChanged: events.Event<() => void>; } //////////////////// @@ -2505,109 +2447,261 @@ export namespace Browser { * @deprecated Check out the {@link declarativeNetRequest} API instead */ export namespace declarativeWebRequest { + /** Filters request headers for various criteria. Multiple criteria are evaluated as a conjunction. */ export interface HeaderFilter { + /** Matches if the header name is equal to the specified string. */ nameEquals?: string | undefined; + /** Matches if the header value contains all of the specified strings. */ valueContains?: string | string[] | undefined; + /** Matches if the header name ends with the specified string. */ nameSuffix?: string | undefined; + /** Matches if the header value ends with the specified string. */ valueSuffix?: string | undefined; + /** Matches if the header value starts with the specified string. */ valuePrefix?: string | undefined; + /** Matches if the header name contains all of the specified strings. */ nameContains?: string | string[] | undefined; + /** Matches if the header value is equal to the specified string. */ valueEquals?: string | undefined; + /** Matches if the header name starts with the specified string. */ namePrefix?: string | undefined; } + /** Adds the response header to the response of this web request. As multiple response headers may share the same name, you need to first remove and then add a new response header in order to replace one. */ export interface AddResponseHeader { + /** HTTP response header name. */ name: string; + /** HTTP response header value. */ value: string; } + /** Removes one or more cookies of response. Note that it is preferred to use the Cookies API because this is computationally less expensive. */ export interface RemoveResponseCookie { - filter: ResponseCookie; + /** Filter for cookies that will be removed. All empty entries are ignored. */ + filter: FilterResponseCookie; } + /** Removes all response headers of the specified names and values. */ export interface RemoveResponseHeader { + /** HTTP request header name (case-insensitive). */ name: string; + /** HTTP request header value (case-insensitive). */ value?: string | undefined; } + /** Matches network events by various criteria. */ export interface RequestMatcher { + /** Matches if the MIME media type of a response (from the HTTP Content-Type header) is contained in the list. */ contentType?: string[] | undefined; - url?: Browser.events.UrlFilter | undefined; + /** Matches if the conditions of the UrlFilter are fulfilled for the URL of the request. */ + url?: events.UrlFilter | undefined; + /** Matches if the MIME media type of a response (from the HTTP Content-Type header) is not contained in the list. */ excludeContentType?: string[] | undefined; + /** Matches if none of the request headers is matched by any of the HeaderFilters. */ + excludeResponseHeaders?: HeaderFilter[] | undefined; + /** Matches if none of the response headers is matched by any of the HeaderFilters. */ excludeResponseHeader?: HeaderFilter[] | undefined; - resourceType?: string | undefined; + /** + * Matches if the conditions of the UrlFilter are fulfilled for the 'first party' URL of the request. The 'first party' URL of a request, when present, can be different from the request's target URL, and describes what is considered 'first party' for the sake of third-party checks for cookies. + * @deprecated since Chrome 82 + */ + firstPartyForCookiesUrl?: events.UrlFilter | undefined; + /** Matches if some of the request headers is matched by one of the HeaderFilters. */ + requestHeaders?: HeaderFilter[] | undefined; + /** Matches if the request type of a request is contained in the list. Requests that cannot match any of the types will be filtered out. */ + resourceType?: `${webRequest.ResourceType}`[] | undefined; + /** Matches if some of the response headers is matched by one of the HeaderFilters. */ responseHeaders?: HeaderFilter[] | undefined; + /** Contains a list of strings describing stages. Allowed values are 'onBeforeRequest', 'onBeforeSendHeaders', 'onHeadersReceived', 'onAuthRequired'. If this attribute is present, then it limits the applicable stages to those listed. Note that the whole condition is only applicable in stages compatible with all attributes. */ + stages?: `${Stage}`[] | undefined; + /** + * If set to true, matches requests that are subject to third-party cookie policies. If set to false, matches all other requests. + * @deprecated since Chrome 87 + */ + thirdPartyForCookies?: boolean | undefined; } + /** Masks all rules that match the specified criteria. */ export interface IgnoreRules { - lowerPriorityThan: number; + /** If set, rules with the specified tag are ignored. This ignoring is not persisted, it affects only rules and their actions of the same network request stage. Note that rules are executed in descending order of their priorities. This action affects rules of lower priority than the current rule. Rules with the same priority may or may not be ignored. */ + hasTag?: string | undefined; + /** If set, rules with a lower priority than the specified value are ignored. This boundary is not persisted, it affects only rules and their actions of the same network request stage. */ + lowerPriorityThan?: number | undefined; } + /** Declarative event action that redirects a network request to an empty document. */ + // eslint-disable-next-line @typescript-eslint/no-empty-interface export interface RedirectToEmptyDocument {} + /** Declarative event action that redirects a network request. */ export interface RedirectRequest { + /** Destination to where the request is redirected. */ redirectUrl: string; } + /** A specification of a cookie in HTTP Responses. */ export interface ResponseCookie { + /** Value of the Domain cookie attribute. */ domain?: string | undefined; + /** Name of a cookie. */ name?: string | undefined; + /** Value of the Expires cookie attribute. */ expires?: string | undefined; + /** Value of the Max-Age cookie attribute */ maxAge?: number | undefined; + /** Value of a cookie, may be padded in double-quotes. */ value?: string | undefined; + /** Value of the Path cookie attribute. */ path?: string | undefined; + /** Existence of the HttpOnly cookie attribute. */ httpOnly?: string | undefined; + /** Existence of the Secure cookie attribute. */ secure?: string | undefined; } + /** Adds a cookie to the response or overrides a cookie, in case another cookie of the same name exists already. Note that it is preferred to use the Cookies API because this is computationally less expensive. */ export interface AddResponseCookie { cookie: ResponseCookie; } + /** Edits one or more cookies of response. Note that it is preferred to use the Cookies API because this is computationally less expensive. */ export interface EditResponseCookie { + /** Filter for cookies that will be modified. All empty entries are ignored. */ filter: ResponseCookie; + /** Attributes that shall be overridden in cookies that machted the filter. Attributes that are set to an empty string are removed. */ modification: ResponseCookie; } + /** Declarative event action that cancels a network request. */ + // eslint-disable-next-line @typescript-eslint/no-empty-interface export interface CancelRequest {} + /** Removes the request header of the specified name. Do not use SetRequestHeader and RemoveRequestHeader with the same header name on the same request. Each request header name occurs only once in each request. */ export interface RemoveRequestHeader { + /** HTTP request header name (case-insensitive). */ name: string; } + /** Edits one or more cookies of request. Note that it is preferred to use the Cookies API because this is computationally less expensive. */ export interface EditRequestCookie { + /** Filter for cookies that will be modified. All empty entries are ignored. */ filter: RequestCookie; + /** Attributes that shall be overridden in cookies that machted the filter. Attributes that are set to an empty string are removed. */ modification: RequestCookie; } - export interface SetRequestHeader { - name: string; - value: string; - } - - export interface RequestCookie { + /** A filter of a cookie in HTTP Responses. */ + export interface FilterResponseCookie { + /** Inclusive lower bound on the cookie lifetime (specified in seconds after current time). Only cookies whose expiration date-time is set to 'now + ageLowerBound' or later fulfill this criterion. Session cookies do not meet the criterion of this filter. The cookie lifetime is calculated from either 'max-age' or 'expires' cookie attributes. If both are specified, 'max-age' is used to calculate the cookie lifetime. */ + ageLowerBound?: number | undefined; + /** Inclusive upper bound on the cookie lifetime (specified in seconds after current time). Only cookies whose expiration date-time is in the interval [now, now + ageUpperBound] fulfill this criterion. Session cookies and cookies whose expiration date-time is in the past do not meet the criterion of this filter. The cookie lifetime is calculated from either 'max-age' or 'expires' cookie attributes. If both are specified, 'max-age' is used to calculate the cookie lifetime. */ + ageUpperBound?: number | undefined; + /** Value of the Domain cookie attribute. */ + domain?: string | undefined; + /** Value of the Expires cookie attribute. */ + expires?: string | undefined; + /** Existence of the HttpOnly cookie attribute. */ + httpOnly?: string | undefined; + /** Value of the Max-Age cookie attribute */ + maxAge?: number | undefined; + /** Name of a cookie. */ name?: string | undefined; + /** Value of the Path cookie attribute. */ + path?: string | undefined; + /** Existence of the Secure cookie attribute. */ + secure?: string | undefined; + /** Filters session cookies. Session cookies have no lifetime specified in any of 'max-age' or 'expires' attributes. */ + session?: boolean | undefined; + /** Value of a cookie, may be padded in double-quotes. */ value?: string | undefined; } + /** Sets the request header of the specified name to the specified value. If a header with the specified name did not exist before, a new one is created. Header name comparison is always case-insensitive. Each request header name occurs only once in each request. */ + export interface SetRequestHeader { + /** HTTP request header name. */ + name: string; + /** HTTP request header value. */ + value: string; + } + + /** A filter or specification of a cookie in HTTP Requests. */ + export interface RequestCookie { + /** Name of a cookie. */ + name?: string | undefined; + /** Value of a cookie, may be padded in double-quotes. */ + value?: string | undefined; + } + + /** Redirects a request by applying a regular expression on the URL. The regular expressions use the RE2 syntax. */ export interface RedirectByRegEx { + /** Destination pattern. */ to: string; + /** A match pattern that may contain capture groups. Capture groups are referenced in the Perl syntax ($1, $2, ...) instead of the RE2 syntax (\1, \2, ...) in order to be closer to JavaScript Regular Expressions. */ from: string; } + /** Declarative event action that redirects a network request to a transparent image. */ + // eslint-disable-next-line @typescript-eslint/no-empty-interface export interface RedirectToTransparentImage {} + /** Adds a cookie to the request or overrides a cookie, in case another cookie of the same name exists already. Note that it is preferred to use the Cookies API because this is computationally less expensive. */ export interface AddRequestCookie { cookie: RequestCookie; } + /** Removes one or more cookies of request. Note that it is preferred to use the Cookies API because this is computationally less expensive. */ export interface RemoveRequestCookie { + /** Filter for cookies that will be removed. All empty entries are ignored. */ filter: RequestCookie; } - export interface RequestedEvent extends Browser.events.Event<() => void> {} + export enum Stage { + ON_AUTH_REQUIRED = "onAuthRequired", + ON_BEFORE_REQUEST = "onBeforeRequest", + ON_BEFORE_SEND_HEADERS = "onBeforeSendHeaders", + ON_HEADERS_RECEIVED = "onHeadersReceived", + } - export var onRequest: RequestedEvent; + export interface MessageDetails { + /** A UUID of the document that made the request. */ + documentId?: string; + /** The lifecycle the document is in. */ + documentLifecycle: extensionTypes.DocumentLifecycle; + /** The value 0 indicates that the request happens in the main frame; a positive value indicates the ID of a subframe in which the request happens. If the document of a (sub-)frame is loaded (`type` is `main_frame` or `sub_frame`), `frameId` indicates the ID of this frame, not the ID of the outer frame. Frame IDs are unique within a tab. */ + frameId: number; + /** The type of frame the navigation occurred in. */ + frameType: extensionTypes.FrameType; + /** The message sent by the calling script. */ + message: string; + /** Standard HTTP method. */ + method: string; + /** A UUID of the parent document owning this frame. This is not set if there is no parent. */ + parentDocumentId?: string; + /** ID of frame that wraps the frame which sent the request. Set to -1 if no parent frame exists. */ + parentFrameId: number; + /** The ID of the request. Request IDs are unique within a browser session. As a result, they could be used to relate different events of the same request. */ + requestId: string; + /** The stage of the network request during which the event was triggered. */ + stage: `${Stage}`; + /** The ID of the tab in which the request takes place. Set to -1 if the request isn't related to a tab. */ + tabId: number; + /** The time when this signal is triggered, in milliseconds since the epoch. */ + timeStamp: number; + /** How the requested resource will be used. */ + type: `${webRequest.ResourceType}`; + url: string; + } + + export interface SendMessageToExtension { + /** The value that will be passed in the message attribute of the dictionary that is passed to the event handler. */ + message: string; + } + + /** Fired when a message is sent via {@link declarativeWebRequest.SendMessageToExtension} from an action of the declarative web request API. */ + export const onMessage: events.Event<(details: MessageDetails) => void>; + + /** Provides the Declarative Event API consisting of `addRules`, `removeRules`, and `getRules`. */ + export const onRequest: events.Event<() => void>; } //////////////////// @@ -2672,15 +2766,12 @@ export namespace Browser { export interface Resource { /** The URL of the resource. */ url: string; - /** - * Gets the content of the resource. - * @param callback A function that receives resource content when the request completes. - */ + /** Gets the content of the resource. */ getContent( callback: ( - /** Content of the resource (potentially encoded) */ + /** Content of the resource (potentially encoded). */ content: string, - /** Empty if content is not encoded, encoding name otherwise. Currently, only base64 is supported. */ + /** Empty if the content is not encoded, encoding name otherwise. Currently, only base64 is supported. */ encoding: string, ) => void, ): void; @@ -2688,33 +2779,24 @@ export namespace Browser { * Sets the content of the resource. * @param content New content of the resource. Only resources with the text type are currently supported. * @param commit True if the user has finished editing the resource, and the new content of the resource should be persisted; false if this is a minor change sent in progress of the user editing the resource. - * @param callback A function called upon request completion. */ setContent( content: string, commit: boolean, callback?: ( - /** - * Set to undefined if the resource content was set successfully; describes error otherwise. - */ + /** Set to undefined if the resource content was set successfully; describes error otherwise. */ error?: object, ) => void, ): void; } export interface ReloadOptions { - /** Optional. If specified, the string will override the value of the User-Agent HTTP header that's sent while loading the resources of the inspected page. The string will also override the value of the navigator.userAgent property that's returned to any scripts that are running within the inspected page. */ + /** If specified, the string will override the value of the `User-Agent` HTTP header that's sent while loading the resources of the inspected page. The string will also override the value of the `navigator.userAgent` property that's returned to any scripts that are running within the inspected page. */ userAgent?: string | undefined; - /** Optional. When true, the loader will ignore the cache for all inspected page resources loaded before the load event is fired. The effect is similar to pressing Ctrl+Shift+R in the inspected window or within the Developer Tools window. */ + /** When true, the loader will bypass the cache for all inspected page resources loaded before the `load` event is fired. The effect is similar to pressing Ctrl+Shift+R in the inspected window or within the Developer Tools window. */ ignoreCache?: boolean | undefined; - /** Optional. If specified, the script will be injected into every frame of the inspected page immediately upon load, before any of the frame's scripts. The script will not be injected after subsequent reloads—for example, if the user presses Ctrl+R. */ + /** If specified, the script will be injected into every frame of the inspected page immediately upon load, before any of the frame's scripts. The script will not be injected after subsequent reloads—for example, if the user presses Ctrl+R. */ injectedScript?: string | undefined; - /** - * Optional. - * If specified, this script evaluates into a function that accepts three string arguments: the source to preprocess, the URL of the source, and a function name if the source is an DOM event handler. The preprocessorerScript function should return a string to be compiled by Chrome in place of the input source. In the case that the source is a DOM event handler, the returned source must compile to a single JS function. - * @deprecated Deprecated since Chrome 41. Please avoid using this parameter, it will be removed soon. - */ - preprocessorScript?: string | undefined; } export interface EvaluationExceptionInfo { @@ -2732,59 +2814,48 @@ export namespace Browser { value: string; } - export interface ResourceAddedEvent extends Browser.events.Event<(resource: Resource) => void> {} - - export interface ResourceContentCommittedEvent - extends Browser.events.Event<(resource: Resource, content: string) => void> - {} - - /** The ID of the tab being inspected. This ID may be used with Browser.tabs.* API. */ - export var tabId: number; + /** The ID of the tab being inspected. This ID may be used with {@link Browser.tabs} API. */ + export const tabId: number; /** Reloads the inspected page. */ export function reload(reloadOptions?: ReloadOptions): void; + /** - * Evaluates a JavaScript expression in the context of the main frame of the inspected page. The expression must evaluate to a JSON-compliant object, otherwise an exception is thrown. The eval function can report either a DevTools-side error or a JavaScript exception that occurs during evaluation. In either case, the result parameter of the callback is undefined. In the case of a DevTools-side error, the isException parameter is non-null and has isError set to true and code set to an error code. In the case of a JavaScript error, isException is set to true and value is set to the string value of thrown object. - * @param expression An expression to evaluate. - * @param callback A function called when evaluation completes. - * Parameter result: The result of evaluation. - * Parameter exceptionInfo: An object providing details if an exception occurred while evaluating the expression. - */ - export function eval( - expression: string, - callback?: (result: T, exceptionInfo: EvaluationExceptionInfo) => void, - ): void; - /** - * Evaluates a JavaScript expression in the context of the main frame of the inspected page. The expression must evaluate to a JSON-compliant object, otherwise an exception is thrown. The eval function can report either a DevTools-side error or a JavaScript exception that occurs during evaluation. In either case, the result parameter of the callback is undefined. In the case of a DevTools-side error, the isException parameter is non-null and has isError set to true and code set to an error code. In the case of a JavaScript error, isException is set to true and value is set to the string value of thrown object. + * Evaluates a JavaScript expression in the context of the main frame of the inspected page. The expression must evaluate to a JSON-compliant object, otherwise an exception is thrown. The eval function can report either a DevTools-side error or a JavaScript exception that occurs during evaluation. In either case, the `result` parameter of the callback is `undefined`. In the case of a DevTools-side error, the `isException` parameter is non-null and has `isError` set to true and `code` set to an error code. In the case of a JavaScript error, `isException` is set to true and `value` is set to the string value of thrown object. + * * @param expression An expression to evaluate. * @param options The options parameter can contain one or more options. * @param callback A function called when evaluation completes. - * Parameter result: The result of evaluation. - * Parameter exceptionInfo: An object providing details if an exception occurred while evaluating the expression. */ - export function eval( + export function eval( expression: string, - options?: EvalOptions, callback?: (result: T, exceptionInfo: EvaluationExceptionInfo) => void, ): void; - /** - * Retrieves the list of resources from the inspected page. - * @param callback A function that receives the list of resources when the request completes. - */ + export function eval( + expression: string, + options: EvalOptions | undefined, + callback?: (result: T, exceptionInfo: EvaluationExceptionInfo) => void, + ): void; + + /** Retrieves the list of resources from the inspected page. */ export function getResources(callback: (resources: Resource[]) => void): void; /** Fired when a new resource is added to the inspected page. */ - export var onResourceAdded: ResourceAddedEvent; + export const onResourceAdded: events.Event<(resource: Resource) => void>; + /** Fired when a new revision of the resource is committed (e.g. user saves an edited version of the resource in the Developer Tools). */ - export var onResourceContentCommitted: ResourceContentCommittedEvent; + export const onResourceContentCommitted: events.Event<(resource: Resource, content: string) => void>; export interface EvalOptions { /** If specified, the expression is evaluated on the iframe whose URL matches the one specified. By default, the expression is evaluated in the top frame of the inspected page. */ frameURL?: string | undefined; - /** Evaluate the expression in the context of the content script of the calling extension, provided that the content script is already injected into the inspected page. If not, the expression is not evaluated and the callback is invoked with the exception parameter set to an object that has the isError field set to true and the code field set to E_NOTFOUND. */ + /** Evaluate the expression in the context of the content script of the calling extension, provided that the content script is already injected into the inspected page. If not, the expression is not evaluated and the callback is invoked with the exception parameter set to an object that has the `isError` field set to true and the `code` field set to `E_NOTFOUND`. */ useContentScriptContext?: boolean | undefined; - /** Evaluate the expression in the context of a content script of an extension that matches the specified origin. If given, contextSecurityOrigin overrides the 'true' setting on userContentScriptContext. */ - contextSecurityOrigin?: string | undefined; + /** + * Evaluate the expression in the context of a content script of an extension that matches the specified origin. If given, scriptExecutionContext overrides the 'true' setting on useContentScriptContext. + * @since Chrome 107 + */ + scriptExecutionContext?: string | undefined; } } @@ -2797,41 +2868,32 @@ export namespace Browser { * Manifest: "devtools_page" */ export namespace devtools.network { - /** Represents a HAR entry for a specific finished request. */ - export interface HAREntry extends HARFormatEntry {} - /** Represents a HAR log that contains all known network requests. */ - export interface HARLog extends HARFormatLog {} /** Represents a network request for a document resource (script, image and so on). See HAR Specification for reference. */ - export interface Request extends Browser.devtools.network.HAREntry { - /** - * Returns content of the response body. - * @param callback A function that receives the response body when the request completes. - */ + export interface Request extends HARFormatEntry { + /** Returns content of the response body. */ getContent( callback: ( - /** Content of the response body (potentially encoded) */ + /** Content of the response body (potentially encoded). */ content: string, - /** Empty if content is not encoded, encoding name otherwise. Currently, only base64 is supported */ + /** Empty if content is not encoded, encoding name otherwise. Currently, only base64 is supported. */ encoding: string, ) => void, ): void; } - export interface RequestFinishedEvent extends Browser.events.Event<(request: Request) => void> {} - - export interface NavigatedEvent extends Browser.events.Event<(url: string) => void> {} - - /** - * Returns HAR log that contains all known network requests. - * @param callback A function that receives the HAR log when the request completes. - * Parameter harLog: A HAR log. See HAR specification for details. - */ - export function getHAR(callback: (harLog: HARLog) => void): void; + /** Returns HAR log that contains all known network requests. */ + export function getHAR( + callback: ( + /** A HAR log. See HAR specification for details. */ + harLog: HARFormatLog, + ) => void, + ): void; /** Fired when a network request is finished and all request data are available. */ - export var onRequestFinished: RequestFinishedEvent; + export const onRequestFinished: events.Event<(request: Request) => void>; + /** Fired when the inspected window navigates to a new page. */ - export var onNavigated: NavigatedEvent; + export const onNavigated: events.Event<(url: string) => void>; } //////////////////// @@ -2842,14 +2904,10 @@ export namespace Browser { * @since Chrome 129 */ export namespace devtools.performance { - export interface ProfilingStartedEvent extends Browser.events.Event<() => void> {} - - export interface ProfilingStoppedEvent extends Browser.events.Event<() => void> {} - - /** Fired when the Performance panel begins recording performance data. */ - export var onProfilingStarted: ProfilingStartedEvent; - /** Fired when the Performance panel stops recording performance data. */ - export var onProfilingStopped: ProfilingStoppedEvent; + /** Fired when the Performance panel starts recording. */ + export const onProfilingStarted: events.Event<() => void>; + /** Fired when the Performance panel stops recording. */ + export const onProfilingStopped: events.Event<() => void>; } //////////////////// @@ -2861,12 +2919,6 @@ export namespace Browser { * Manifest: "devtools_page" */ export namespace devtools.panels { - export interface PanelShownEvent extends Browser.events.Event<(window: Window) => void> {} - - export interface PanelHiddenEvent extends Browser.events.Event<() => void> {} - - export interface PanelSearchEvent extends Browser.events.Event<(action: string, queryString?: string) => void> {} - /** Represents a panel created by an extension. */ export interface ExtensionPanel { /** @@ -2877,15 +2929,18 @@ export namespace Browser { */ createStatusBarButton(iconPath: string, tooltipText: string, disabled: boolean): Button; /** Fired when the user switches to the panel. */ - onShown: PanelShownEvent; + onShown: events.Event<(window: Window) => void>; /** Fired when the user switches away from the panel. */ - onHidden: PanelHiddenEvent; + onHidden: events.Event<() => void>; /** Fired upon a search action (start of a new search, search result navigation, or search being canceled). */ - onSearch: PanelSearchEvent; + onSearch: events.Event<(action: string, queryString?: string) => void>; + /** + * Shows the panel by activating the corresponding tab. + * @since Chrome 140 + */ + show(): void; } - export interface ButtonClickedEvent extends Browser.events.Event<() => void> {} - /** A button created by the extension. */ export interface Button { /** @@ -2896,38 +2951,14 @@ export namespace Browser { */ update(iconPath?: string | null, tooltipText?: string | null, disabled?: boolean | null): void; /** Fired when the button is clicked. */ - onClicked: ButtonClickedEvent; + onClicked: events.Event<() => void>; } - export interface SelectionChangedEvent extends Browser.events.Event<() => void> {} - /** Represents the Elements panel. */ export interface ElementsPanel { /** * Creates a pane within panel's sidebar. * @param title Text that is displayed in sidebar caption. - * @param callback A callback invoked when the sidebar is created. - */ - createSidebarPane( - title: string, - callback?: ( - /** An ExtensionSidebarPane object for created sidebar pane */ - result: ExtensionSidebarPane, - ) => void, - ): void; - /** Fired when an object is selected in the panel. */ - onSelectionChanged: SelectionChangedEvent; - } - - /** - * @since Chrome 41 - * Represents the Sources panel. - */ - export interface SourcesPanel { - /** - * Creates a pane within panel's sidebar. - * @param title Text that is displayed in sidebar caption. - * @param callback A callback invoked when the sidebar is created. */ createSidebarPane( title: string, @@ -2937,115 +2968,125 @@ export namespace Browser { ) => void, ): void; /** Fired when an object is selected in the panel. */ - onSelectionChanged: SelectionChangedEvent; + onSelectionChanged: events.Event<() => void>; } - export interface ExtensionSidebarPaneShownEvent extends Browser.events.Event<(window: Window) => void> {} - - export interface ExtensionSidebarPaneHiddenEvent extends Browser.events.Event<() => void> {} + /** Represents the Sources panel. */ + export interface SourcesPanel { + /** + * Creates a pane within panel's sidebar. + * @param title Text that is displayed in sidebar caption. + */ + createSidebarPane( + title: string, + callback?: ( + /** An ExtensionSidebarPane object for created sidebar pane. */ + result: ExtensionSidebarPane, + ) => void, + ): void; + /** Fired when an object is selected in the panel. */ + onSelectionChanged: events.Event<() => void>; + } /** A sidebar created by the extension. */ export interface ExtensionSidebarPane { /** * Sets the height of the sidebar. - * @param height A CSS-like size specification, such as '100px' or '12ex'. + * @param height A CSS-like size specification, such as `100px` or `12ex`. */ setHeight(height: string): void; /** * Sets an expression that is evaluated within the inspected page. The result is displayed in the sidebar pane. * @param expression An expression to be evaluated in context of the inspected page. JavaScript objects and DOM nodes are displayed in an expandable tree similar to the console/watch. * @param rootTitle An optional title for the root of the expression tree. - * @param callback A callback invoked after the sidebar pane is updated with the expression evaluation results. - */ - setExpression(expression: string, rootTitle?: string, callback?: () => void): void; - /** - * Sets an expression that is evaluated within the inspected page. The result is displayed in the sidebar pane. - * @param expression An expression to be evaluated in context of the inspected page. JavaScript objects and DOM nodes are displayed in an expandable tree similar to the console/watch. - * @param callback A callback invoked after the sidebar pane is updated with the expression evaluation results. */ setExpression(expression: string, callback?: () => void): void; + setExpression(expression: string, rootTitle: string | undefined, callback?: () => void): void; /** * Sets a JSON-compliant object to be displayed in the sidebar pane. * @param jsonObject An object to be displayed in context of the inspected page. Evaluated in the context of the caller (API client). * @param rootTitle An optional title for the root of the expression tree. - * @param callback A callback invoked after the sidebar is updated with the object. - */ - setObject(jsonObject: { [key: string]: unknown }, rootTitle?: string, callback?: () => void): void; - /** - * Sets a JSON-compliant object to be displayed in the sidebar pane. - * @param jsonObject An object to be displayed in context of the inspected page. Evaluated in the context of the caller (API client). - * @param callback A callback invoked after the sidebar is updated with the object. */ setObject(jsonObject: { [key: string]: unknown }, callback?: () => void): void; + setObject( + jsonObject: { [key: string]: unknown }, + rootTitle: string | undefined, + callback?: () => void, + ): void; /** * Sets an HTML page to be displayed in the sidebar pane. * @param path Relative path of an extension page to display within the sidebar. */ setPage(path: string): void; /** Fired when the sidebar pane becomes visible as a result of user switching to the panel that hosts it. */ - onShown: ExtensionSidebarPaneShownEvent; + onShown: events.Event<(window: Window) => void>; /** Fired when the sidebar pane becomes hidden as a result of the user switching away from the panel that hosts the sidebar pane. */ - onHidden: ExtensionSidebarPaneHiddenEvent; + onHidden: events.Event<() => void>; } - /** Elements panel. */ - export var elements: ElementsPanel; /** - * @since Chrome 38 - * Sources panel. + * Theme used by DevTools. + * @since Chrome 99 */ - export var sources: SourcesPanel; + export type Theme = "default" | "dark"; + + /** Elements panel. */ + export const elements: ElementsPanel; + + /** Sources panel. */ + export const sources: SourcesPanel; /** * Creates an extension panel. * @param title Title that is displayed next to the extension icon in the Developer Tools toolbar. * @param iconPath Path of the panel's icon relative to the extension directory. * @param pagePath Path of the panel's HTML page relative to the extension directory. - * @param callback A function that is called when the panel is created. - * Parameter panel: An ExtensionPanel object representing the created panel. */ export function create( title: string, iconPath: string, pagePath: string, - callback?: (panel: ExtensionPanel) => void, + callback?: ( + /** An ExtensionPanel object representing the created panel. */ + panel: ExtensionPanel, + ) => void, ): void; - /** - * Specifies the function to be called when the user clicks a resource link in the Developer Tools window. To unset the handler, either call the method with no parameters or pass null as the parameter. - * @param callback A function that is called when the user clicks on a valid resource link in Developer Tools window. Note that if the user clicks an invalid URL or an XHR, this function is not called. - * Parameter resource: A devtools.inspectedWindow.Resource object for the resource that was clicked. - * Parameter lineNumber: Specifies the line number within the resource that was clicked. - */ + + /** Specifies the function to be called when the user clicks a resource link in the Developer Tools window. To unset the handler, either call the method with no parameters or pass null as the parameter. */ export function setOpenResourceHandler( - callback?: (resource: Browser.devtools.inspectedWindow.Resource, lineNumber: number) => void, + callback?: ( + /** A {@link devtools.inspectedWindow.Resource} object for the resource that was clicked. */ + resource: Browser.devtools.inspectedWindow.Resource, + /** Specifies the line number within the resource that was clicked. */ + lineNumber: number, + ) => void, ): void; + /** - * @since Chrome 38 - * Requests DevTools to open a URL in a Developer Tools panel. - * @param url The URL of the resource to open. - * @param lineNumber Specifies the line number to scroll to when the resource is loaded. - * @param callback A function that is called when the resource has been successfully loaded. + * Specifies the function to be called when the current theme changes in DevTools. To unset the handler, either call the method with no parameters or pass `null` as the parameter. + * @since Chrome 99 */ - export function openResource(url: string, lineNumber: number, callback?: () => void): void; + export function setThemeChangeHandler(callback?: (theme: Theme) => void): void; + /** - * @since Chrome 96 * Requests DevTools to open a URL in a Developer Tools panel. * @param url The URL of the resource to open. * @param lineNumber Specifies the line number to scroll to when the resource is loaded. * @param columnNumber Specifies the column number to scroll to when the resource is loaded. - * @param callback A function that is called when the resource has been successfully loaded. */ + export function openResource(url: string, lineNumber: number, callback?: () => void): void; export function openResource( url: string, lineNumber: number, - columnNumber: number, - callback?: (response: unknown) => unknown, + columnNumber: number | undefined, + callback?: () => void, ): void; + /** - * @since Chrome 59 * The name of the color theme set in user's DevTools settings. + * @since Chrome 59 */ - export var themeName: "default" | "dark"; + export const themeName: Theme; } //////////////////// @@ -3723,6 +3764,7 @@ export namespace Browser { SAFE = "safe", /** The user has accepted the dangerous download. */ ACCEPTED = "accepted", + /** Enterprise-related values. */ ALLOWLISTED_BY_POLICY = "allowlistedByPolicy", ASYNC_SCANNING = "asyncScanning", ASYNC_LOCAL_PASSWORD_SCANNING = "asyncLocalPasswordScanning", @@ -3737,6 +3779,8 @@ export namespace Browser { PROMPT_FOR_LOCAL_PASSWORD_SCANNING = "promptForLocalPasswordScanning", ACCOUNT_COMPROMISE = "accountCompromise", BLOCKED_SCAN_FAILED = "blockedScanFailed", + /** For use by the Secure Enterprise Browser extension. When required, Chrome will block the download to disc and download the file directly to Google Drive. */ + FORCE_SAVE_TO_GDRIVE = "forceSaveToGdrive", } export interface DownloadItem { @@ -4200,44 +4244,47 @@ export namespace Browser { */ export namespace enterprise.deviceAttributes { /** - * @description Fetches the value of the device identifier of the directory API, that is generated by the server and identifies the cloud record of the device for querying in the cloud directory API. - * @param callback Called with the device identifier of the directory API when received. + * Fetches the value of the device identifier of the directory API, that is generated by the server and identifies the cloud record of the device for querying in the cloud directory API. If the current user is not affiliated, returns an empty string. + * + * Can return its result via Promise in Manifest V3 or later since Chrome 96. */ + export function getDirectoryDeviceId(): Promise; export function getDirectoryDeviceId(callback: (deviceId: string) => void): void; + /** + * Fetches the device's serial number. Please note the purpose of this API is to administrate the device (e.g. generating Certificate Sign Requests for device-wide certificates). This API may not be used for tracking devices without the consent of the device's administrator. If the current user is not affiliated, returns an empty string. + * + * Can return its result via Promise in Manifest V3 or later since Chrome 96. * @since Chrome 66 - * @description - * Fetches the device's serial number. - * Please note the purpose of this API is to administrate the device - * (e.g. generating Certificate Sign Requests for device-wide certificates). - * This API may not be used for tracking devices without the consent of the device's administrator. - * If the current user is not affiliated, returns an empty string. - * @param callback Called with the serial number of the device. */ + export function getDeviceSerialNumber(): Promise; export function getDeviceSerialNumber(callback: (serialNumber: string) => void): void; + /** + * Fetches the administrator-annotated Asset Id. If the current user is not affiliated or no Asset Id has been set by the administrator, returns an empty string. + * + * Can return its result via Promise in Manifest V3 or later since Chrome 96. * @since Chrome 66 - * @description - * Fetches the administrator-annotated Asset Id. - * If the current user is not affiliated or no Asset Id has been set by the administrator, returns an empty string. - * @param callback Called with the Asset ID of the device. */ + export function getDeviceAssetId(): Promise; export function getDeviceAssetId(callback: (assetId: string) => void): void; + /** + * Fetches the administrator-annotated Location. If the current user is not affiliated or no Annotated Location has been set by the administrator, returns an empty string. + * + * Can return its result via Promise in Manifest V3 or later since Chrome 96. * @since Chrome 66 - * @description - * Fetches the administrator-annotated Location. - * If the current user is not affiliated or no Annotated Location has been set by the administrator, returns an empty string. - * @param callback Called with the Annotated Location of the device. */ + export function getDeviceAnnotatedLocation(): Promise; export function getDeviceAnnotatedLocation(callback: (annotatedLocation: string) => void): void; + /** + * Fetches the device's hostname as set by DeviceHostnameTemplate policy. If the current user is not affiliated or no hostname has been set by the enterprise policy, returns an empty string. + * + * Can return its result via Promise in Manifest V3 or later since Chrome 96. * @since Chrome 82 - * @description - * Fetches the device's hostname as set by DeviceHostnameTemplate policy. - * If the current user is not affiliated or no hostname has been set by the enterprise policy, returns an empty string. - * @param callback Called with the hostname of the device. */ + export function getDeviceHostname(): Promise; export function getDeviceHostname(callback: (hostname: string) => void): void; } @@ -4400,7 +4447,8 @@ export namespace Browser { * Unregisters currently registered rules. * @param ruleIdentifiers If an array is passed, only rules with identifiers contained in this array are unregistered. */ - removeRules(ruleIdentifiers?: string[] | undefined, callback?: () => void): void; + removeRules(ruleIdentifiers: string[] | undefined, callback?: () => void): void; + removeRules(callback?: () => void): void; /** * Registers rules to handle events. @@ -4445,117 +4493,114 @@ export namespace Browser { * 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. */ export namespace extension { + /** + * The type of extension view. + * @since Chrome 44 + */ + export enum ViewType { + TAB = "tab", + POPUP = "popup", + } + export interface FetchProperties { /** - * Optional. - * Chrome 54+ * Find a view according to a tab id. If this field is omitted, returns all views. + * @since Chrome 54 */ tabId?: number | undefined; - /** Optional. The window to restrict the search to. If omitted, returns all views. */ + /** The window to restrict the search to. If omitted, returns all views. */ windowId?: number | undefined; - /** Optional. The type of view to get. If omitted, returns all views (including background pages and tabs). Valid values: 'tab', 'notification', 'popup'. */ - type?: string | undefined; + /** The type of view to get. If omitted, returns all views (including background pages and tabs). */ + type?: `${ViewType}` | undefined; } - export interface LastError { - /** Description of the error that has taken place. */ - message: string; - } - - export interface OnRequestEvent extends - Browser.events.Event< - | ((request: any, sender: runtime.MessageSender, sendResponse: (response: any) => void) => void) - | ((sender: runtime.MessageSender, sendResponse: (response: any) => void) => void) - > - {} + /** 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. */ + export const inIncognitoContext: boolean; /** - * @since Chrome 7 - * 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. + * Set for the lifetime of a callback if an ansychronous extension api has resulted in an error. If no error has occurred lastError will be `undefined`. + * @deprecated since Chrome 58. Please use {@link runtime.lastError} */ - export var inIncognitoContext: boolean; - /** Set for the lifetime of a callback if an ansychronous extension api has resulted in an error. If no error has occurred lastError will be undefined. */ - export var lastError: LastError; + export const lastError: runtime.LastError | undefined; /** Returns the JavaScript 'window' object for the background page running inside the current extension. Returns null if the extension has no background page. */ export function getBackgroundPage(): Window | null; + /** * 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. + * @deprecated since Chrome 58. Please use {@link runtime.getURL} */ export function getURL(path: string): string; - /** - * 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 Chrome Extension Gallery. - * @since Chrome 9 - */ + + /** 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 Chrome Extension Gallery. */ export function setUpdateUrlData(data: string): void; + /** Returns an array of the JavaScript 'window' objects for each of the pages running inside the current extension. */ export function getViews(fetchProperties?: FetchProperties): Window[]; + /** - * Retrieves the state of the extension's access to the 'file://' scheme (as determined by the user-controlled 'Allow access to File URLs' checkbox. - * @since Chrome 12 - * @return The `isAllowedFileSchemeAccess` method provides its result via callback or returned as a `Promise` (MV3 only). + * Retrieves the state of the extension's access to the 'file://' scheme. This corresponds to the user-controlled per-extension 'Allow access to File URLs' setting accessible via the `chrome://extensions` page. + * + * Can return its result via Promise in Manifest V3 or later since Chrome 99. */ export function isAllowedFileSchemeAccess(): 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. - * @since Chrome 12 - * Parameter isAllowedAccess: True if the extension can access the 'file://' scheme, false otherwise. - */ export function isAllowedFileSchemeAccess(callback: (isAllowedAccess: boolean) => void): void; + /** - * Retrieves the state of the extension's access to Incognito-mode (as determined by the user-controlled 'Allowed in Incognito' checkbox. - * @since Chrome 12 - * @return The `isAllowedIncognitoAccess` method provides its result via callback or returned as a `Promise` (MV3 only). + * Retrieves the state of the extension's access to Incognito-mode. This corresponds to the user-controlled per-extension 'Allowed in Incognito' setting accessible via the `chrome://extensions` page. + * + * Can return its result via Promise in Manifest V3 or later since Chrome 99. */ export function isAllowedIncognitoAccess(): Promise; - /** - * Retrieves the state of the extension's access to Incognito-mode (as determined by the user-controlled 'Allowed in Incognito' checkbox. - * @since Chrome 12 - * Parameter isAllowedAccess: True if the extension has access to Incognito mode, false otherwise. - */ export function isAllowedIncognitoAccess(callback: (isAllowedAccess: boolean) => void): void; + /** - * Sends a single request to other listeners within the extension. Similar to runtime.connect, but only sends a single request with an optional response. The extension.onRequest event is fired in each page of the extension. - * @deprecated Deprecated since Chrome 33. Please use runtime.sendMessage. + * Sends a single request to other listeners within the extension. Similar to {@link runtime.connect}, but only sends a single request with an optional response. The {@link extension.onRequest} event is fired in each page of the extension. + * + * MV2 only * @param extensionId The extension ID of the extension you want to connect to. If omitted, default is your own extension. - * @param responseCallback If you specify the responseCallback parameter, it should be a function that looks like this: - * function(any response) {...}; - * Parameter response: The JSON response object sent by the handler of the request. If an error occurs while connecting to the extension, the callback will be called with no arguments and runtime.lastError will be set to the error message. + * @deprecated Please use {@link runtime.sendMessage} */ export function sendRequest( - extensionId: string, + extensionId: string | undefined, request: Request, - responseCallback?: (response: Response) => void, + callback?: (response: Response) => void, ): void; - /** - * Sends a single request to other listeners within the extension. Similar to runtime.connect, but only sends a single request with an optional response. The extension.onRequest event is fired in each page of the extension. - * @deprecated Deprecated since Chrome 33. Please use runtime.sendMessage. - * @param responseCallback If you specify the responseCallback parameter, it should be a function that looks like this: - * function(any response) {...}; - * Parameter response: The JSON response object sent by the handler of the request. If an error occurs while connecting to the extension, the callback will be called with no arguments and runtime.lastError will be set to the error message. - */ export function sendRequest( request: Request, - responseCallback?: (response: Response) => void, + callback?: (response: Response) => void, ): void; + /** - * Returns an array of the JavaScript 'window' objects for each of the tabs running inside the current extension. If windowId is specified, returns only the 'window' objects of tabs attached to the specified window. - * @deprecated Deprecated since Chrome 33. Please use extension.getViews {type: "tab"}. + * Returns an array of the JavaScript 'window' objects for each of the tabs running inside the current extension. If `windowId` is specified, returns only the 'window' objects of tabs attached to the specified window. + * + * MV2 only + * @deprecated Please use {@link extension.getViews} `{type: "tab"}`. */ export function getExtensionTabs(windowId?: number): Window[]; /** * Fired when a request is sent from either an extension process or a content script. - * @deprecated Deprecated since Chrome 33. Please use runtime.onMessage. + * + * MV2 only + * @deprecated Please use {@link runtime.onMessage}. */ - export var onRequest: OnRequestEvent; + export const onRequest: Browser.events.Event< + | ((request: any, sender: runtime.MessageSender, sendResponse: (response: any) => void) => void) + | ((sender: runtime.MessageSender, sendResponse: (response: any) => void) => void) + >; + /** * Fired when a request is sent from another extension. - * @deprecated Deprecated since Chrome 33. Please use runtime.onMessageExternal. + * + * MV2 only + * @deprecated Please use {@link runtime.onMessageExternal}. */ - export var onRequestExternal: OnRequestEvent; + export const onRequestExternal: Browser.events.Event< + | ((request: any, sender: runtime.MessageSender, sendResponse: (response: any) => void) => void) + | ((sender: runtime.MessageSender, sendResponse: (response: any) => void) => void) + >; } //////////////////// @@ -4563,6 +4608,9 @@ export namespace Browser { //////////////////// /** The `Browser.extensionTypes` API contains type declarations for Chrome extensions. */ export namespace extensionTypes { + /** @since Chrome 139 */ + export type ColorArray = [number, number, number, number]; + /** * The origin of injected CSS. * @since Chrome 66 @@ -4646,47 +4694,16 @@ export namespace Browser { * @platform ChromeOS only */ export namespace fileBrowserHandler { - export interface SelectionParams { - /** - * Optional. - * List of file extensions that the selected file can have. The list is also used to specify what files to be shown in the select file dialog. Files with the listed extensions are only shown in the dialog. Extensions should not include the leading '.'. Example: ['jpg', 'png'] - * @since Chrome 23 - */ - allowedFileExtensions?: string[] | undefined; - /** Suggested name for the file. */ - suggestedName: string; - } - - export interface SelectionResult { - /** Optional. Selected file entry. It will be null if a file hasn't been selected. */ - entry?: object | null | undefined; - /** Whether the file has been selected. */ - success: boolean; - } - /** Event details payload for fileBrowserHandler.onExecute event. */ export interface FileHandlerExecuteEventDetails { - /** Optional. The ID of the tab that raised this event. Tab IDs are unique within a browser session. */ - tab_id?: number | undefined; + /** The ID of the tab that raised this event. Tab IDs are unique within a browser session. */ + tab_id?: number; /** Array of Entry instances representing files that are targets of this action (selected in ChromeOS file browser). */ entries: any[]; } - export interface FileBrowserHandlerExecuteEvent - extends Browser.events.Event<(id: string, details: FileHandlerExecuteEventDetails) => void> - {} - - /** - * Prompts user to select file path under which file should be saved. When the file is selected, file access permission required to use the file (read, write and create) are granted to the caller. The file will not actually get created during the function call, so function caller must ensure its existence before using it. The function has to be invoked with a user gesture. - * @since Chrome 21 - * @param selectionParams Parameters that will be used while selecting the file. - * @param callback Function called upon completion. - * Parameter result: Result of the method. - */ - export function selectFile(selectionParams: SelectionParams, callback: (result: SelectionResult) => void): void; - /** Fired when file system action is executed from ChromeOS file browser. */ - export var onExecute: FileBrowserHandlerExecuteEvent; + export const onExecute: events.Event<(id: string, details: FileHandlerExecuteEventDetails) => void>; } //////////////////// @@ -5469,212 +5486,382 @@ export namespace Browser { fontId: string; } - export interface DefaultFontSizeDetails { + /** A CSS generic font family. */ + export enum GenericFamily { + STANDARD = "standard", + SANSSERIF = "sansserif", + SERIF = "serif", + FIXED = "fixed", + CURSIVE = "cursive", + FANTASY = "fantasy", + MATH = "math", + } + + export enum LevelOfControl { + /** Cannot be controlled by any extension */ + NOT_CONTROLLABLE = "not_controllable", + /** Controlled by extensions with higher precedence */ + CONTROLLED_BY_OTHER_EXTENSIONS = "controlled_by_other_extensions", + /** Can be controlled by this extension */ + CONTROLLABLE_BY_THIS_EXTENSION = "controllable_by_this_extension", + /** Controlled by this extension */ + CONTROLLED_BY_THIS_EXTENSION = "controlled_by_this_extension", + } + + /** An ISO 15924 script code. The default, or global, script is represented by script code "Zyyy". */ + export enum ScriptCode { + AFAK = "Afak", + ARAB = "Arab", + ARMI = "Armi", + ARMN = "Armn", + AVST = "Avst", + BALI = "Bali", + BAMU = "Bamu", + BASS = "Bass", + BATK = "Batk", + BENG = "Beng", + BLIS = "Blis", + BOPO = "Bopo", + BRAH = "Brah", + BRAI = "Brai", + BUGI = "Bugi", + BUHD = "Buhd", + CAKM = "Cakm", + CANS = "Cans", + CARI = "Cari", + CHAM = "Cham", + CHER = "Cher", + CIRT = "Cirt", + COPT = "Copt", + CPRT = "Cprt", + CYRL = "Cyrl", + CYRS = "Cyrs", + DEVA = "Deva", + DSRT = "Dsrt", + DUPL = "Dupl", + EGYD = "Egyd", + EGYH = "Egyh", + EGYP = "Egyp", + ELBA = "Elba", + ETHI = "Ethi", + GEOK = "Geok", + GEOR = "Geor", + GLAG = "Glag", + GOTH = "Goth", + GRAN = "Gran", + GREK = "Grek", + GUJR = "Gujr", + GURU = "Guru", + HANG = "Hang", + HANI = "Hani", + HANO = "Hano", + HANS = "Hans", + HANT = "Hant", + HEBR = "Hebr", + HLUW = "Hluw", + HMNG = "Hmng", + HUNG = "Hung", + INDS = "Inds", + ITAL = "Ital", + JAVA = "Java", + JPAN = "Jpan", + JURC = "Jurc", + KALI = "Kali", + KHAR = "Khar", + KHMR = "Khmr", + KHOJ = "Khoj", + KNDA = "Knda", + KPEL = "Kpel", + KTHI = "Kthi", + LANA = "Lana", + LAOO = "Laoo", + LATF = "Latf", + LATG = "Latg", + LATN = "Latn", + LEPC = "Lepc", + LIMB = "Limb", + LINA = "Lina", + LINB = "Linb", + LISU = "Lisu", + LOMA = "Loma", + LYCI = "Lyci", + LYDI = "Lydi", + MAND = "Mand", + MANI = "Mani", + MAYA = "Maya", + MEND = "Mend", + MERC = "Merc", + MERO = "Mero", + MLYM = "Mlym", + MONG = "Mong", + MOON = "Moon", + MROO = "Mroo", + MTEI = "Mtei", + MYMR = "Mymr", + NARB = "Narb", + NBAT = "Nbat", + NKGB = "Nkgb", + NKOO = "Nkoo", + NSHU = "Nshu", + OGAM = "Ogam", + OLCK = "Olck", + ORKH = "Orkh", + ORYA = "Orya", + OSMA = "Osma", + PALM = "Palm", + PERM = "Perm", + PHAG = "Phag", + PHLI = "Phli", + PHLP = "Phlp", + PHLV = "Phlv", + PHNX = "Phnx", + PLRD = "Plrd", + PRTI = "Prti", + RJNG = "Rjng", + RORO = "Roro", + RUNR = "Runr", + SAMR = "Samr", + SARA = "Sara", + SARB = "Sarb", + SAUR = "Saur", + SGNW = "Sgnw", + SHAW = "Shaw", + SHRD = "Shrd", + SIND = "Sind", + SINH = "Sinh", + SORA = "Sora", + SUND = "Sund", + SYLO = "Sylo", + SYRC = "Syrc", + SYRE = "Syre", + SYRJ = "Syrj", + SYRN = "Syrn", + TAGB = "Tagb", + TAKR = "Takr", + TALE = "Tale", + TALU = "Talu", + TAML = "Taml", + TANG = "Tang", + TAVT = "Tavt", + TELU = "Telu", + TENG = "Teng", + TFNG = "Tfng", + TGLG = "Tglg", + THAA = "Thaa", + THAI = "Thai", + TIBT = "Tibt", + TIRH = "Tirh", + UGAR = "Ugar", + VAII = "Vaii", + VISP = "Visp", + WARA = "Wara", + WOLE = "Wole", + XPEO = "Xpeo", + XSUX = "Xsux", + YIII = "Yiii", + ZMTH = "Zmth", + ZSYM = "Zsym", + ZYYY = "Zyyy", + } + + export interface ClearFontDetails { + /** The generic font family for which the font should be cleared. */ + genericFamily: `${GenericFamily}`; + /** The script for which the font should be cleared. If omitted, the global script font setting is cleared. */ + script?: `${ScriptCode}` | undefined; + } + + export interface GetFontDetails { + /** The generic font family for which the font should be retrieved. */ + genericFamily: `${GenericFamily}`; + /** The script for which the font should be retrieved. If omitted, the font setting for the global script (script code "Zyyy") is retrieved. */ + script?: `${ScriptCode}` | undefined; + } + + export interface SetFontDetails { + /** The font ID. The empty string means to fallback to the global script font setting. */ + fontId: string; + /** The generic font family for which the font should be set. */ + genericFamily: `${GenericFamily}`; + /** The script code which the font should be set. If omitted, the font setting for the global script (script code "Zyyy") is set. */ + script?: `${ScriptCode}` | undefined; + } + + export interface FontChangedResult { + /** The generic font family for which the font setting has changed. */ + genericFamily: `${GenericFamily}`; + /** The level of control this extension has over the setting. */ + levelOfControl: `${LevelOfControl}`; + /** Optional. The script code for which the font setting has changed. */ + script?: `${ScriptCode}`; + /** The font ID. See the description in {@link getFont}. */ + fontId: string; + } + + export interface FontResult { + /** The level of control this extension has over the setting. */ + levelOfControl: `${LevelOfControl}`; + /** The font ID. Rather than the literal font ID preference value, this may be the ID of the font that the system resolves the preference value to. So, `fontId` can differ from the font passed to {@link setFont}, if, for example, the font is not available on the system. The empty string signifies fallback to the global script font setting. */ + fontId: string; + } + + export interface FontSizeResult { /** The font size in pixels. */ pixelSize: number; - } - - export interface FontDetails { - /** The generic font family for the font. */ - genericFamily: - | "cursive" - | "fantasy" - | "fixed" - | "sansserif" - | "serif" - | "standard"; - /** Optional. The script for the font. If omitted, the global script font setting is affected. */ - script?: string | undefined; - } - - export interface FullFontDetails { - /** The generic font family for which the font setting has changed. */ - genericFamily: string; /** The level of control this extension has over the setting. */ - levelOfControl: string; - /** Optional. The script code for which the font setting has changed. */ - script?: string | undefined; - /** The font ID. See the description in getFont. */ - fontId: string; - } - - export interface FontDetailsResult { - /** The level of control this extension has over the setting. */ - levelOfControl: string; - /** The font ID. Rather than the literal font ID preference value, this may be the ID of the font that the system resolves the preference value to. So, fontId can differ from the font passed to setFont, if, for example, the font is not available on the system. The empty string signifies fallback to the global script font setting. */ - fontId: string; + levelOfControl: `${LevelOfControl}`; } export interface FontSizeDetails { /** The font size in pixels. */ pixelSize: number; - /** The level of control this extension has over the setting. */ - levelOfControl: string; } - export interface SetFontSizeDetails { - /** The font size in pixels. */ - pixelSize: number; - } - - export interface SetFontDetails extends FontDetails { - /** The font ID. The empty string means to fallback to the global script font setting. */ - fontId: string; - } - - export interface DefaultFixedFontSizeChangedEvent - extends Browser.events.Event<(details: FontSizeDetails) => void> - {} - - export interface DefaultFontSizeChangedEvent extends Browser.events.Event<(details: FontSizeDetails) => void> {} - - export interface MinimumFontSizeChangedEvent extends Browser.events.Event<(details: FontSizeDetails) => void> {} - - export interface FontChangedEvent extends Browser.events.Event<(details: FullFontDetails) => void> {} - /** * Sets the default font size. - * @return The `setDefaultFontSize` method provides its result via callback or returned as a `Promise` (MV3 only). It has no parameters. + * + * Can return its result via Promise in Manifest V3 or later since Chrome 96. */ - export function setDefaultFontSize(details: DefaultFontSizeDetails): Promise; - /** - * Sets the default font size. - */ - export function setDefaultFontSize(details: DefaultFontSizeDetails, callback: () => void): void; + export function setDefaultFontSize(details: FontSizeDetails): Promise; + export function setDefaultFontSize(details: FontSizeDetails, callback: () => void): void; + /** * Gets the font for a given script and generic font family. - * @return The `getFont` method provides its result via callback or returned as a `Promise` (MV3 only). + * + * Can return its result via Promise in Manifest V3 or later since Chrome 96. */ - export function getFont(details: FontDetails): Promise; - /** - * Gets the font for a given script and generic font family. - */ - export function getFont(details: FontDetails, callback: (details: FontDetailsResult) => void): void; + export function getFont(details: GetFontDetails): Promise; + export function getFont(details: GetFontDetails, callback: (details: FontResult) => void): void; + /** * Gets the default font size. * @param details This parameter is currently unused. - * @return The `getDefaultFontSize` method provides its result via callback or returned as a `Promise` (MV3 only). + * + * Can return its result via Promise in Manifest V3 or later since Chrome 96. */ - export function getDefaultFontSize(details?: unknown): Promise; - /** - * Gets the default font size. - * @param details This parameter is currently unused. - */ - export function getDefaultFontSize(callback: (options: FontSizeDetails) => void): void; - export function getDefaultFontSize(details: unknown, callback: (options: FontSizeDetails) => void): void; + export function getDefaultFontSize(details?: { [key: string]: unknown }): Promise; + export function getDefaultFontSize(callback: (options: FontSizeResult) => void): void; + export function getDefaultFontSize( + details: { [key: string]: unknown } | undefined, + callback: (options: FontSizeResult) => void, + ): void; + /** * Gets the minimum font size. * @param details This parameter is currently unused. - * @return The `getMinimumFontSize` method provides its result via callback or returned as a `Promise` (MV3 only). + * + * Can return its result via Promise in Manifest V3 or later since Chrome 96. */ - export function getMinimumFontSize(details?: unknown): Promise; - /** - * Gets the minimum font size. - * @param details This parameter is currently unused. - */ - export function getMinimumFontSize(callback: (options: FontSizeDetails) => void): void; - export function getMinimumFontSize(details: unknown, callback: (options: FontSizeDetails) => void): void; + export function getMinimumFontSize(details?: { [key: string]: unknown }): Promise; + export function getMinimumFontSize(callback: (options: FontSizeResult) => void): void; + export function getMinimumFontSize( + details: { [key: string]: unknown } | undefined, + callback: (options: FontSizeResult) => void, + ): void; + /** * Sets the minimum font size. - * @return The `setMinimumFontSize` method provides its result via callback or returned as a `Promise` (MV3 only). It has no parameters. + * + * Can return its result via Promise in Manifest V3 or later since Chrome 96. */ - export function setMinimumFontSize(details: SetFontSizeDetails): Promise; - /** - * Sets the minimum font size. - */ - export function setMinimumFontSize(details: SetFontSizeDetails, callback: () => void): void; + export function setMinimumFontSize(details: FontSizeDetails): Promise; + export function setMinimumFontSize(details: FontSizeDetails, callback: () => void): void; + /** * Gets the default size for fixed width fonts. * @param details This parameter is currently unused. - * @return The `getDefaultFixedFontSize` method provides its result via callback or returned as a `Promise` (MV3 only). + * + * Can return its result via Promise in Manifest V3 or later since Chrome 96. */ - export function getDefaultFixedFontSize(details?: unknown): Promise; - /** - * Gets the default size for fixed width fonts. - * @param details This parameter is currently unused. - */ - export function getDefaultFixedFontSize(callback: (details: FontSizeDetails) => void): void; - export function getDefaultFixedFontSize(details: unknown, callback: (details: FontSizeDetails) => void): void; - /** - * Clears the default font size set by this extension, if any. - * @param details This parameter is currently unused. - * @return The `clearDefaultFontSize` method provides its result via callback or returned as a `Promise` (MV3 only). It has no parameters. - */ - export function clearDefaultFontSize(details?: unknown): Promise; + export function getDefaultFixedFontSize(details?: { [key: string]: unknown }): Promise; + export function getDefaultFixedFontSize(callback: (details: FontSizeResult) => void): void; + export function getDefaultFixedFontSize( + details: { [key: string]: unknown } | undefined, + callback: (details: FontSizeResult) => void, + ): void; + /** * Clears the default font size set by this extension, if any. * @param details This parameter is currently unused. + * + * Can return its result via Promise in Manifest V3 or later since Chrome 96. */ + export function clearDefaultFontSize(details?: { [key: string]: unknown }): Promise; export function clearDefaultFontSize(callback: () => void): void; - export function clearDefaultFontSize(details: unknown, callback: () => void): void; + export function clearDefaultFontSize( + details: { [key: string]: unknown } | undefined, + callback: () => void, + ): void; + /** * Sets the default size for fixed width fonts. - * @return The `setDefaultFixedFontSize` method provides its result via callback or returned as a `Promise` (MV3 only). It has no parameters. + * + * Can return its result via Promise in Manifest V3 or later since Chrome 96. */ - export function setDefaultFixedFontSize(details: SetFontSizeDetails): Promise; - /** - * Sets the default size for fixed width fonts. - */ - export function setDefaultFixedFontSize(details: SetFontSizeDetails, callback: () => void): void; + export function setDefaultFixedFontSize(details: FontSizeDetails): Promise; + export function setDefaultFixedFontSize(details: FontSizeDetails, callback: () => void): void; + /** * Clears the font set by this extension, if any. - * @return The `clearFont` method provides its result via callback or returned as a `Promise` (MV3 only). It has no parameters. + * + * Can return its result via Promise in Manifest V3 or later since Chrome 96. */ - export function clearFont(details: FontDetails): Promise; - /** - * Clears the font set by this extension, if any. - */ - export function clearFont(details: FontDetails, callback: () => void): void; + export function clearFont(details: ClearFontDetails): Promise; + export function clearFont(details: ClearFontDetails, callback: () => void): void; + /** * Sets the font for a given script and generic font family. - * @return The `setFont` method provides its result via callback or returned as a `Promise` (MV3 only). It has no parameters. + * + * Can return its result via Promise in Manifest V3 or later since Chrome 96. */ export function setFont(details: SetFontDetails): Promise; - /** - * Sets the font for a given script and generic font family. - */ export function setFont(details: SetFontDetails, callback: () => void): void; + /** * Clears the minimum font size set by this extension, if any. * @param details This parameter is currently unused. - * @return The `clearMinimumFontSize` method provides its result via callback or returned as a `Promise` (MV3 only). It has no parameters. - */ - export function clearMinimumFontSize(details?: unknown): Promise; - /** - * Clears the minimum font size set by this extension, if any. - * @param details This parameter is currently unused. + * + * Can return its result via Promise in Manifest V3 or later since Chrome 96. */ + export function clearMinimumFontSize(details?: { [key: string]: unknown }): Promise; export function clearMinimumFontSize(callback: () => void): void; - export function clearMinimumFontSize(details: unknown, callback: () => void): void; + export function clearMinimumFontSize( + details: { [key: string]: unknown } | undefined, + callback: () => void, + ): void; + /** * Gets a list of fonts on the system. - * @return The `getFontList` method provides its result via callback or returned as a `Promise` (MV3 only). + * + * Can return its result via Promise in Manifest V3 or later since Chrome 96. */ export function getFontList(): Promise; - /** - * Gets a list of fonts on the system. - */ export function getFontList(callback: (results: FontName[]) => void): void; + /** * Clears the default fixed font size set by this extension, if any. * @param details This parameter is currently unused. - * @return The `clearDefaultFixedFontSize` method provides its result via callback or returned as a `Promise` (MV3 only). It has no parameters. + * + * Can return its result via Promise in Manifest V3 or later since Chrome 96. */ - export function clearDefaultFixedFontSize(details: unknown): Promise; - /** - * Clears the default fixed font size set by this extension, if any. - * @param details This parameter is currently unused. - */ - export function clearDefaultFixedFontSize(details: unknown, callback: () => void): void; + export function clearDefaultFixedFontSize(details?: { [key: string]: unknown }): Promise; + export function clearDefaultFixedFontSize(callback: () => void): void; + export function clearDefaultFixedFontSize( + details: { [key: string]: unknown } | undefined, + callback: () => void, + ): void; /** Fired when the default fixed font size setting changes. */ - export var onDefaultFixedFontSizeChanged: DefaultFixedFontSizeChangedEvent; + export const onDefaultFixedFontSizeChanged: events.Event<(details: FontSizeResult) => void>; + /** Fired when the default font size setting changes. */ - export var onDefaultFontSizeChanged: DefaultFontSizeChangedEvent; + export const onDefaultFontSizeChanged: events.Event<(details: FontSizeResult) => void>; + /** Fired when the minimum font size setting changes. */ - export var onMinimumFontSizeChanged: MinimumFontSizeChangedEvent; + export const onMinimumFontSizeChanged: events.Event<(details: FontSizeResult) => void>; + /** Fired when a font setting changes. */ - export var onFontChanged: FontChangedEvent; + export const onFontChanged: events.Event<(details: FontChangedResult) => void>; } //////////////////// @@ -5766,46 +5953,81 @@ export namespace Browser { /** An object encapsulating one visit to a URL. */ export interface VisitItem { /** The transition type for this visit from its referrer. */ - transition: string; - /** Optional. When this visit occurred, represented in milliseconds since the epoch. */ - visitTime?: number | undefined; + transition: `${TransitionType}`; + /** + * True if the visit originated on this device. False if it was synced from a different device + * @since Chrome 115 + */ + isLocal: boolean; + /** When this visit occurred, represented in milliseconds since the epoch. */ + visitTime?: number; /** The unique identifier for this visit. */ visitId: string; /** The visit ID of the referrer. */ referringVisitId: string; - /** The unique identifier for the item. */ + /** The unique identifier for the corresponding {@link history.HistoryItem}. */ id: string; } /** An object encapsulating one result of a history query. */ export interface HistoryItem { - /** Optional. The number of times the user has navigated to this page by typing in the address. */ - typedCount?: number | undefined; - /** Optional. The title of the page when it was last loaded. */ - title?: string | undefined; - /** Optional. The URL navigated to by a user. */ - url?: string | undefined; - /** Optional. When this page was last loaded, represented in milliseconds since the epoch. */ - lastVisitTime?: number | undefined; - /** Optional. The number of times the user has navigated to this page. */ - visitCount?: number | undefined; + /** The number of times the user has navigated to this page by typing in the address. */ + typedCount?: number; + /** The title of the page when it was last loaded. */ + title?: string; + /** The URL navigated to by a user. */ + url?: string; + /** When this page was last loaded, represented in milliseconds since the epoch. */ + lastVisitTime?: number; + /** The number of times the user has navigated to this page. */ + visitCount?: number; /** The unique identifier for the item. */ id: string; } + /** + * The transition type for this visit from its referrer. + * @since Chrome 44 + */ + export enum TransitionType { + /** The user arrived at this page by clicking a link on another page. */ + LINK = "link", + /** The user arrived at this page by typing the URL in the address bar. This is also used for other explicit navigation actions. */ + TYPED = "typed", + /** The user arrived at this page through a suggestion in the UI, for example, through a menu item. */ + AUTO_BOOKMARK = "auto_bookmark", + /** The user arrived at this page through subframe navigation that they didn't request, such as through an ad loading in a frame on the previous page. These don't always generate new navigation entries in the back and forward menus. */ + AUTO_SUBFRAME = "auto_subframe", + /** The user arrived at this page by selecting something in a subframe. */ + MANUAL_SUBFRAME = "manual_subframe", + /** The user arrived at this page by typing in the address bar and selecting an entry that didn't look like a URL, such as a Google Search suggestion. For example, a match might have the URL of a Google Search result page, but it might appear to the user as "Search Google for ...". These are different from typed navigations because the user didn't type or see the destination URL. They're also related to keyword navigations. */ + GENERATED = "generated", + /** The page was specified in the command line or is the start page. */ + AUTO_TOPLEVEL = "auto_toplevel", + /** The user arrived at this page by filling out values in a form and submitting the form. Not all form submissions use this transition type. */ + FORM_SUBMIT = "form_submit", + /** The user reloaded the page, either by clicking the reload button or by pressing Enter in the address bar. Session restore and Reopen closed tab also use this transition type. */ + RELOAD = "reload", + /** The URL for this page was generated from a replaceable keyword other than the default search provider. */ + KEYWORD = "keyword", + /** Corresponds to a visit generated for a keyword. */ + KEYWORD_GENERATED = "keyword_generated", + } + export interface HistoryQuery { - /** A free-text query to the history service. Leave empty to retrieve all pages. */ + /** A free-text query to the history service. Leave this empty to retrieve all pages. */ text: string; - /** Optional. The maximum number of results to retrieve. Defaults to 100. */ + /** The maximum number of results to retrieve. Defaults to 100. */ maxResults?: number | undefined; - /** Optional. Limit results to those visited after this date, represented in milliseconds since the epoch. */ + /** Limit results to those visited after this date, represented in milliseconds since the epoch. If property is not specified, it will default to 24 hours. */ startTime?: number | undefined; - /** Optional. Limit results to those visited before this date, represented in milliseconds since the epoch. */ + /** Limit results to those visited before this date, represented in milliseconds since the epoch. */ endTime?: number | undefined; } - export interface Url { - /** The URL for the operation. It must be in the format as returned from a call to history.search. */ + /** @since Chrome 88 */ + export interface UrlDetails { + /** The URL for the operation. It must be in the format as returned from a call to {@link history.search}. */ url: string; } @@ -5819,73 +6041,62 @@ export namespace Browser { export interface RemovedResult { /** True if all history was removed. If true, then urls will be empty. */ allHistory: boolean; - /** Optional. */ - urls?: string[] | undefined; + urls?: string[]; } - export interface HistoryVisitedEvent extends Browser.events.Event<(result: HistoryItem) => void> {} - - export interface HistoryVisitRemovedEvent extends Browser.events.Event<(removed: RemovedResult) => void> {} - /** * Searches the history for the last visit time of each page matching the query. - * @return The `search` method provides its result via callback or returned as a `Promise` (MV3 only). + * + * Can return its result via Promise in Manifest V3 or later since Chrome 96. */ export function search(query: HistoryQuery): Promise; - /** - * Searches the history for the last visit time of each page matching the query. - */ export function search(query: HistoryQuery, callback: (results: HistoryItem[]) => void): void; + /** * Adds a URL to the history at the current time with a transition type of "link". - * @return The `addUrl` method provides its result via callback or returned as a `Promise` (MV3 only). It has no parameters. + * + * Can return its result via Promise in Manifest V3 or later since Chrome 96. */ - export function addUrl(details: Url): Promise; - /** - * Adds a URL to the history at the current time with a transition type of "link". - */ - export function addUrl(details: Url, callback: () => void): void; + export function addUrl(details: UrlDetails): Promise; + export function addUrl(details: UrlDetails, callback: () => void): void; + /** * Removes all items within the specified date range from the history. Pages will not be removed from the history unless all visits fall within the range. - * @return The `deleteRange` method provides its result via callback or returned as a `Promise` (MV3 only). It has no parameters. + * + * Can return its result via Promise in Manifest V3 or later since Chrome 96. */ export function deleteRange(range: Range): Promise; - /** - * Removes all items within the specified date range from the history. Pages will not be removed from the history unless all visits fall within the range. - */ export function deleteRange(range: Range, callback: () => void): void; + /** * Deletes all items from the history. - * @return The `deleteAll` method provides its result via callback or returned as a `Promise` (MV3 only). It has no parameters. + * + * Can return its result via Promise in Manifest V3 or later since Chrome 96. */ export function deleteAll(): Promise; - /** - * Deletes all items from the history. - */ export function deleteAll(callback: () => void): void; - /** - * Retrieves information about visits to a URL. - * @return The `getVisits` method provides its result via callback or returned as a `Promise` (MV3 only). - */ - export function getVisits(details: Url): Promise; - /** - * Retrieves information about visits to a URL. - */ - export function getVisits(details: Url, callback: (results: VisitItem[]) => void): void; - /** - * Removes all occurrences of the given URL from the history. - * @return The `deleteUrl` method provides its result via callback or returned as a `Promise` (MV3 only). It has no parameters. - */ - export function deleteUrl(details: Url): Promise; - /** - * Removes all occurrences of the given URL from the history. - */ - export function deleteUrl(details: Url, callback: () => void): void; - /** Fired when a URL is visited, providing the HistoryItem data for that URL. This event fires before the page has loaded. */ - export var onVisited: HistoryVisitedEvent; - /** Fired when one or more URLs are removed from the history service. When all visits have been removed the URL is purged from history. */ - export var onVisitRemoved: HistoryVisitRemovedEvent; + /** + * Retrieves information about visits to a URL. + * + * Can return its result via Promise in Manifest V3 or later since Chrome 96. + */ + export function getVisits(details: UrlDetails): Promise; + export function getVisits(details: UrlDetails, callback: (results: VisitItem[]) => void): void; + + /** + * Removes all occurrences of the given URL from the history. + * + * Can return its result via Promise in Manifest V3 or later since Chrome 96. + */ + export function deleteUrl(details: UrlDetails): Promise; + export function deleteUrl(details: UrlDetails, callback: () => void): void; + + /** Fired when a URL is visited, providing the {@link HistoryItem} data for that URL. This event fires before the page has loaded. */ + export const onVisited: events.Event<(result: HistoryItem) => void>; + + /** Fired when one or more URLs are removed from history. When all visits have been removed the URL is purged from history. */ + export const onVisitRemoved: events.Event<(removed: RemovedResult) => void>; } //////////////////// @@ -5897,58 +6108,56 @@ export namespace Browser { * Manifest: "default_locale" */ export namespace i18n { - /** Holds detected ISO language code and its percentage in the input string */ export interface DetectedLanguage { - /** An ISO language code such as 'en' or 'fr'. - * For a complete list of languages supported by this method, see [kLanguageInfoTable]{@link https://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 */ language: string; - /** The percentage of the detected language */ percentage: number; } - /** Holds detected language reliability and array of DetectedLanguage */ + /** Holds detected language reliability and array of {@link DetectedLanguage} */ export interface LanguageDetectionResult { /** CLD detected language reliability */ isReliable: boolean; - /** Array of detectedLanguage */ languages: DetectedLanguage[]; } + /** @since Chrome 79 */ + export interface GetMessageOptions { + /** Escape `<` in translation to `<`. This applies only to the message itself, not to the placeholders. Developers might want to use this if the translation is used in an HTML context. Closure Templates used with Closure Compiler generate this automatically. */ + escapeLt?: boolean | undefined; + } + /** - * Gets the accept-languages of the browser. This is different from the locale used by the browser; to get the locale, use i18n.getUILanguage. - * @return The `getAcceptLanguages` method provides its result via callback or returned as a `Promise` (MV3 only). - * @since MV3 + * Gets the accept-languages of the browser. This is different from the locale used by the browser; to get the locale, use {@link i18n.getUILanguage}. + * + * Can return its result via Promise in Manifest V3 or later since Chrome 99. */ export function getAcceptLanguages(): Promise; - /** - * Gets the accept-languages of the browser. This is different from the locale used by the browser; to get the locale, use i18n.getUILanguage. - * Parameter languages: Array of the accept languages of the browser, such as en-US,en,zh-CN - */ export function getAcceptLanguages(callback: (languages: string[]) => void): void; + /** - * 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 Optional. Up to 9 substitution strings, if the message requires any. - */ - export function getMessage(messageName: string, substitutions?: string | string[]): string; - /** - * Gets the browser UI language of the browser. This is different from i18n.getAcceptLanguages which returns the preferred user languages. - * @since Chrome 35 + * 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 Up to 9 substitution strings, if the message requires any. */ + export function getMessage(messageName: string, substitutions?: string | Array): string; + export function getMessage( + messageName: string, + substitutions: string | Array | undefined, + options?: GetMessageOptions, + ): string; + + /** Gets the browser UI language of the browser. This is different from {@link i18n.getAcceptLanguages} which returns the preferred user languages. */ export function getUILanguage(): string; /** Detects the language of the provided text using CLD. * @param text User input string to be translated. - * @return The `detectLanguage` method provides its result via callback or returned as a `Promise` (MV3 only). - * @since MV3 + * + * Can return its result via Promise in Manifest V3 or later since Chrome 99. + * @since Chrome 47 */ export function detectLanguage(text: string): Promise; - /** Detects the language of the provided text using CLD. - * @param text User input string to be translated. - */ export function detectLanguage(text: string, callback: (result: LanguageDetectionResult) => void): void; } @@ -6143,38 +6352,43 @@ export namespace Browser { * Permissions: "idle" */ export namespace idle { - export type IdleState = "active" | "idle" | "locked"; - export interface IdleStateChangedEvent extends Browser.events.Event<(newState: IdleState) => void> {} + /** @since Chrome 44 */ + export enum IdleState { + ACTIVE = "active", + IDLE = "idle", + LOCKED = "locked", + } /** * Returns "locked" if the system is locked, "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. - * @since Chrome 116 + * + * Can return its result via Promise in Manifest V3 or later since Chrome 116. */ - export function queryState(detectionIntervalInSeconds: number): Promise; - /** - * Returns "locked" if the system is locked, "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. - * @since Chrome 25 - */ - export function queryState(detectionIntervalInSeconds: number, callback: (newState: IdleState) => void): void; + export function queryState(detectionIntervalInSeconds: number): Promise<`${IdleState}`>; + export function queryState( + detectionIntervalInSeconds: number, + callback: (newState: `${IdleState}`) => void, + ): void; /** * 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. - * @since Chrome 25 * @param intervalInSeconds Threshold, in seconds, used to determine when the system is in an idle state. */ export function setDetectionInterval(intervalInSeconds: number): void; /** - * Gets the time, in seconds, it takes until the screen is locked automatically while idle. Returns a zero duration if the screen is never locked automatically. Currently supported on Chrome OS only. - * Parameter delay: Time, in seconds, until the screen is locked automatically while idle. This is zero if the screen never locks automatically. + * Gets the time, in seconds, it takes until the screen is locked automatically while idle. Returns a zero duration if the screen is never locked automatically. + * + * Can return its result via Promise in Manifest V3 or later since Chrome 116. + * @since Chrome 73 + * @platform ChromeOS only */ export function getAutoLockDelay(): Promise; export function getAutoLockDelay(callback: (delay: number) => void): void; /** Fired when the system changes to an active, idle or locked state. The event fires with "locked" if the screen is locked or the screensaver activates, "idle" if the system is unlocked and the user has not generated any input for a specified number of seconds, and "active" when the user generates input on an idle system. */ - export var onStateChanged: IdleStateChangedEvent; + export const onStateChanged: events.Event<(newState: `${IdleState}`) => void>; } //////////////////// @@ -6187,96 +6401,86 @@ export namespace Browser { * @platform ChromeOS only */ export namespace input.ime { - /** See http://www.w3.org/TR/DOM-Level-3-Events/#events-KeyboardEvent */ + /** See https://www.w3.org/TR/uievents/#events-KeyboardEvent */ export interface KeyboardEvent { - /** - * Optional. - * Whether or not the SHIFT key is pressed. - */ + /** Whether or not the SHIFT key is pressed. */ shiftKey?: boolean | undefined; - /** - * Optional. - * Whether or not the ALT key is pressed. - */ + /** Whether or not the ALT key is pressed. */ altKey?: boolean | undefined; /** - * Optional. * Whether or not the ALTGR key is pressed. * @since Chrome 79 */ altgrKey?: boolean | undefined; /** - * Optional. - * The ID of the request. Use the requestId param from the onKeyEvent event instead. - * @deprecated since Chrome 79. + * The ID of the request + * @deprecated Use the `requestId` param from the `onKeyEvent` event instead. */ requestId?: string | undefined; - /** Value of the key being pressed */ + /** Value of the key being pressed. */ key: string; - /** - * Optional. - * Whether or not the CTRL key is pressed. - */ + /** Whether or not the CTRL key is pressed. */ ctrlKey?: boolean | undefined; /** One of keyup or keydown. */ - type: string; - /** - * Optional. - * The extension ID of the sender of this keyevent. - * @since Chrome 34 - */ + type: `${KeyboardEventType}`; + /** The extension ID of the sender of this keyevent. */ extensionId?: string | undefined; - /** - * Optional. - * Value of the physical key being pressed. The value is not affected by current keyboard layout or modifier state. - * @since Chrome 26 - */ + /** Value of the physical key being pressed. The value is not affected by current keyboard layout or modifier state. */ code: string; - /** - * Optional. - * The deprecated HTML keyCode, which is system- and implementation-dependent numerical code signifying the unmodified identifier associated with the key pressed. - * @since Chrome 37 - */ + /** The deprecated HTML keyCode, which is system- and implementation-dependent numerical code signifying the unmodified identifier associated with the key pressed. */ keyCode?: number | undefined; - /** - * Optional. - * Whether or not the CAPS_LOCK is enabled. - * @since Chrome 29 - */ + /** Whether or not the CAPS_LOCK is enabled. */ capsLock?: boolean | undefined; } + /** @since Chrome 44 */ + export enum KeyboardEventType { + KEYUP = "keyup", + KEYDOWN = "keydown", + } + /** * The auto-capitalize type of the text field. * @since Chrome 69 */ - export type AutoCapitalizeType = "characters" | "words" | "sentences"; + export enum AutoCapitalizeType { + CHARACTERS = "characters", + WORDS = "words", + SENTENCES = "sentences", + } + + /** + * Type of value this text field edits, (Text, Number, URL, etc) + * @since Chrome 44 + */ + export enum InputContextType { + TEXT = "text", + SEARCH = "search", + TEL = "tel", + URL = "url", + EMAIL = "email", + NUMBER = "number", + PASSWORD = "password", + NULL = "null", + } + /** Describes an input Context */ export interface InputContext { /** This is used to specify targets of text field operations. This ID becomes invalid as soon as onBlur is called. */ contextID: number; /** Type of value this text field edits, (Text, Number, URL, etc) */ - type: string; - /** - * Whether the text field wants auto-correct. - * @since Chrome 40 - */ + type: `${InputContextType}`; + /** Whether the text field wants auto-correct. */ autoCorrect: boolean; - /** - * Whether the text field wants auto-complete. - * @since Chrome 40 - */ + /** Whether the text field wants auto-complete. */ autoComplete: boolean; - /** - * Whether the text field wants spell-check. - * @since Chrome 40 - */ + /** Whether the text field wants spell-check. */ spellCheck: boolean; /** * The auto-capitalize type of the text field. * @since Chrome 69 */ - autoCapitalize: AutoCapitalizeType; + autoCapitalize: `${AutoCapitalizeType}`; /** * Whether text entered into the text field should be used to improve typing suggestions for the user. * @since Chrome 68 @@ -6284,18 +6488,15 @@ export namespace Browser { shouldDoLearning: boolean; } - /** - * A menu item used by an input method to interact with the user from the language menu. - * @since Chrome 30 - */ + /** A menu item used by an input method to interact with the user from the language menu. */ export interface MenuItem { /** String that will be passed to callbacks referencing this MenuItem. */ id: string; - /** Optional. Text displayed in the menu for this item. */ + /** Text displayed in the menu for this item. */ label?: string | undefined; - /** Optional. The type of menu item. */ - style?: string | undefined; - /** Optional. Indicates this item is visible. */ + /** The type of menu item. */ + style?: `${MenuItemStyle}` | undefined; + /** Indicates this item is visible. */ visible?: boolean | undefined; /** Indicates this item should be drawn with a check. */ checked?: boolean | undefined; @@ -6303,11 +6504,14 @@ export namespace Browser { enabled?: boolean | undefined; } - export interface ImeParameters { - /** MenuItems to use. */ - items: MenuItem[]; - /** ID of the engine to use */ - engineID: string; + /** + * The type of menu item. Radio buttons between separators are considered grouped. + * @since Chrome 44 + */ + export enum MenuItemStyle { + CHECK = "check", + RADIO = "radio", + SEPARATOR = "separator", } export interface CommitTextParameters { @@ -6329,25 +6533,13 @@ export namespace Browser { candidate: string; /** The candidate's id */ id: number; - /** - * Optional. - * The id to add these candidates under - */ + /** The id to add these candidates under */ parentId?: number | undefined; - /** - * Optional. - * Short string displayed to next to the candidate, often the shortcut key or index - */ + /** Short string displayed to next to the candidate, often the shortcut key or index */ label?: string | undefined; - /** - * Optional. - * Additional text describing the candidate - */ + /** Additional text describing the candidate */ annotation?: string | undefined; - /** - * Optional. - * The usage or detail description of word. - */ + /** The usage or detail description of word. */ usage?: CandidateUsage | undefined; } @@ -6364,7 +6556,7 @@ export namespace Browser { /** Index of the character to end this segment after. */ end: number; /** The type of the underline to modify this segment. */ - style: string; + style: `${UnderlineStyle}`; } export interface CompositionParameters { @@ -6372,79 +6564,111 @@ export namespace Browser { contextID: number; /** Text to set */ text: string; - /** Optional. List of segments and their associated types. */ + /** List of segments and their associated types. */ segments?: CompositionParameterSegment[] | undefined; /** Position in the text of the cursor. */ cursor: number; - /** Optional. Position in the text that the selection starts at. */ + /** Position in the text that the selection starts at. */ selectionStart?: number | undefined; - /** Optional. Position in the text that the selection ends at. */ + /** Position in the text that the selection ends at. */ selectionEnd?: number | undefined; } - export interface MenuItemParameters { + /** @since Chrome 88 */ + export interface MenuParameters { + /** MenuItems to add or update. They will be added in the order they exist in the array. */ items: MenuItem[]; - engineId: string; + /** ID of the engine to use. */ + engineID: string; } - /** Type of the assistive window. */ - export type AssistiveWindowType = "undo"; + /** + * Which mouse buttons was clicked. + * @since Chrome 44 + */ + export enum MouseButton { + LEFT = "left", + MIDDLE = "middle", + RIGHT = "right", + } - /** ID of a button in an assistive window. */ - export type AssistiveWindowButton = "undo" | "addToDictionary"; + /** + * The screen type under which the IME is activated. + * @since Chrome 44 + */ + export enum ScreenType { + NORMAL = "normal", + LOGIN = "login", + LOCK = "lock", + SECONDARY_LOGIN = "secondary-login", + } - /** Properties of an assistive window. */ + /** + * The type of the underline to modify this segment. + * @since Chrome 44 + */ + export enum UnderlineStyle { + UNDERLINE = "underline", + DOUBLE_UNDERLINE = "doubleUnderline", + NO_UNDERLINE = "noUnderline", + } + + /** + * Where to display the candidate window. If set to 'cursor', the window follows the cursor. If set to 'composition', the window is locked to the beginning of the composition. + * @since Chrome 44 + */ + export enum WindowPosition { + CURSOR = "cursor", + COMPOSITION = "composition", + } + + /** Type of assistive window. */ + export enum AssistiveWindowType { + UNDO = "undo", + } + + /** + * ID of a button in an assistive window. + * @since Chrome 85 + */ + export enum AssistiveWindowButton { + UNDO = "undo", + ADD_TO_DICTIONARY = "addToDictionary", + } + + /** + * Properties of the assistive window. + * @since Chrome 85 + */ export interface AssistiveWindowProperties { - type: AssistiveWindowType; + type: `${AssistiveWindowType}`; + /** Sets true to show AssistiveWindow, sets false to hide. */ visible: boolean; + /** Strings for ChromeVox to announce */ announceString?: string | undefined; } export interface CandidateWindowParameterProperties { - /** - * Optional. - * True to show the cursor, false to hide it. - */ + /** True to show the cursor, false to hide it. */ cursorVisible?: boolean | undefined; - /** - * Optional. - * True if the candidate window should be rendered vertical, false to make it horizontal. - */ + /** True if the candidate window should be rendered vertical, false to make it horizontal. */ vertical?: boolean | undefined; - /** - * Optional. - * The number of candidates to display per page. - */ + /** The number of candidates to display per page. */ pageSize?: number | undefined; - /** - * Optional. - * True to display the auxiliary text, false to hide it. - */ + /** True to display the auxiliary text, false to hide it. */ auxiliaryTextVisible?: boolean | undefined; - /** - * Optional. - * Text that is shown at the bottom of the candidate window. - */ + /** Text that is shown at the bottom of the candidate window. */ auxiliaryText?: string | undefined; - /** - * Optional. - * True to show the Candidate window, false to hide it. - */ + /** True to show the Candidate window, false to hide it. */ visible?: boolean | undefined; + /** Where to display the candidate window. */ + windowPosition?: `${WindowPosition}` | undefined; /** - * Optional. - * Where to display the candidate window. - * @since Chrome 28 - */ - windowPosition?: string | undefined; - /** - * Optional. * The index of the current chosen candidate out of total candidates. * @since Chrome 84 */ currentCandidateIndex?: number | undefined; /** - * Optional. * The total number of candidates for the candidate window. * @since Chrome 84 */ @@ -6487,179 +6711,215 @@ export namespace Browser { length: number; } + export interface AssistiveWindowButtonHighlightedParameters { + /** The text for the screenreader to announce. */ + announceString?: string | undefined; + /** The ID of the button */ + buttonID: `${AssistiveWindowButton}`; + /** ID of the context owning the assistive window. */ + contextID: number; + /** Whether the button should be highlighted. */ + highlighted: boolean; + /** The window type the button belongs to. */ + windowType: `${AssistiveWindowType}`; + } + + export interface AssistiveWindowPropertiesParameters { + /** ID of the context owning the assistive window. */ + contextID: number; + /** Properties of the assistive window. */ + properties: AssistiveWindowProperties; + } + export interface SurroundingTextInfo { - /** The text around cursor. */ + /** The text around the cursor. This is only a subset of all text in the input field. */ text: string; /** The ending position of the selection. This value indicates caret position if there is no selection. */ focus: number; - /** The beginning position of the selection. This value indicates caret position if is no selection. */ + /** + * The offset position of `text`. Since `text` only includes a subset of text around the cursor, offset indicates the absolute position of the first character of `text`. + * @since Chrome 46 + */ + offset: number; + /** The beginning position of the selection. This value indicates caret position if there is no selection. */ anchor: number; } export interface AssistiveWindowButtonClickedDetails { /** The ID of the button clicked. */ - buttonID: AssistiveWindowButton; + buttonID: `${AssistiveWindowButton}`; /** The type of the assistive window. */ - windowType: AssistiveWindowType; + windowType: `${AssistiveWindowType}`; } - export interface BlurEvent extends Browser.events.Event<(contextID: number) => void> {} - - export interface AssistiveWindowButtonClickedEvent - extends Browser.events.Event<(details: AssistiveWindowButtonClickedDetails) => void> - {} - - export interface CandidateClickedEvent - extends Browser.events.Event<(engineID: string, candidateID: number, button: string) => void> - {} - - export interface KeyEventEvent - extends Browser.events.Event<(engineID: string, keyData: KeyboardEvent, requestId: string) => void> - {} - - export interface DeactivatedEvent extends Browser.events.Event<(engineID: string) => void> {} - - export interface InputContextUpdateEvent extends Browser.events.Event<(context: InputContext) => void> {} - - export interface ActivateEvent extends Browser.events.Event<(engineID: string, screen: string) => void> {} - - export interface FocusEvent extends Browser.events.Event<(context: InputContext) => void> {} - - export interface MenuItemActivatedEvent extends Browser.events.Event<(engineID: string, name: string) => void> {} - - export interface SurroundingTextChangedEvent - extends Browser.events.Event<(engineID: string, surroundingInfo: SurroundingTextInfo) => void> - {} - - export interface InputResetEvent extends Browser.events.Event<(engineID: string) => void> {} - /** * Adds the provided menu items to the language menu when this IME is active. + * + * Can return its result via Promise in Manifest V3 or later since Chrome 111. */ - export function setMenuItems(parameters: ImeParameters, callback?: () => void): void; + export function setMenuItems(parameters: MenuParameters): Promise; + export function setMenuItems(parameters: MenuParameters, callback: () => void): void; + /** * Commits the provided text to the current input. - * @param callback Called when the operation completes with a boolean indicating if the text was accepted or not. On failure, Browser.runtime.lastError is set. + * + * Can return its result via Promise in Manifest V3 or later since Chrome 111. */ - export function commitText(parameters: CommitTextParameters, callback?: (success: boolean) => void): void; + export function commitText(parameters: CommitTextParameters): Promise; + export function commitText(parameters: CommitTextParameters, callback: (success: boolean) => void): void; + /** * Sets the current candidate list. This fails if this extension doesn't own the active IME - * @param callback Called when the operation completes. + * + * Can return its result via Promise in Manifest V3 or later since Chrome 111. */ - export function setCandidates(parameters: CandidatesParameters, callback?: (success: boolean) => void): void; + export function setCandidates(parameters: CandidatesParameters): Promise; + export function setCandidates(parameters: CandidatesParameters, callback: (success: boolean) => void): void; + /** * Set the current composition. If this extension does not own the active IME, this fails. - * @param callback Called when the operation completes with a boolean indicating if the text was accepted or not. On failure, Browser.runtime.lastError is set. + * + * Can return its result via Promise in Manifest V3 or later since Chrome 111. */ - export function setComposition(parameters: CompositionParameters, callback?: (success: boolean) => void): void; + export function setComposition(parameters: CompositionParameters): Promise; + export function setComposition(parameters: CompositionParameters, callback: (success: boolean) => void): void; + /** * Updates the state of the MenuItems specified - * @param callback Called when the operation completes + * + * Can return its result via Promise in Manifest V3 or later since Chrome 111. */ - export function updateMenuItems(parameters: MenuItemParameters, callback?: () => void): void; + export function updateMenuItems(parameters: MenuParameters): Promise; + export function updateMenuItems(parameters: MenuParameters, callback: () => void): void; + /** * Shows/Hides an assistive window with the given properties. - * @param parameters - * @param callback Called when the operation completes. + * + * Can return its result via Promise in Manifest V3 or later since Chrome 111. */ export function setAssistiveWindowProperties( - parameters: { - contextID: number; - properties: Browser.input.ime.AssistiveWindowProperties; - }, - callback?: (success: boolean) => void, + parameters: AssistiveWindowPropertiesParameters, + ): Promise; + export function setAssistiveWindowProperties( + parameters: AssistiveWindowPropertiesParameters, + callback: (success: boolean) => void, ): void; + /** * Highlights/Unhighlights a button in an assistive window. - * @param parameters - * @param callback Called when the operation completes. On failure, Browser.runtime.lastError is set. + * + * Can return its result via Promise in Manifest V3 or later since Chrome 111. */ export function setAssistiveWindowButtonHighlighted( - parameters: { - contextID: number; - buttonID: Browser.input.ime.AssistiveWindowButton; - windowType: Browser.input.ime.AssistiveWindowType; - announceString?: string | undefined; - highlighted: boolean; - }, - callback?: () => void, + parameters: AssistiveWindowButtonHighlightedParameters, + ): Promise; + export function setAssistiveWindowButtonHighlighted( + parameters: AssistiveWindowButtonHighlightedParameters, + callback: () => void, ): void; + /** * Sets the properties of the candidate window. This fails if the extension doesn't own the active IME - * @param callback Called when the operation completes. + * + * Can return its result via Promise in Manifest V3 or later since Chrome 111. */ + export function setCandidateWindowProperties(parameters: CandidateWindowParameter): Promise; export function setCandidateWindowProperties( parameters: CandidateWindowParameter, - callback?: (success: boolean) => void, + callback: (success: boolean) => void, ): void; + /** * Clear the current composition. If this extension does not own the active IME, this fails. - * @param callback Called when the operation completes with a boolean indicating if the text was accepted or not. On failure, Browser.runtime.lastError is set. + * + * Can return its result via Promise in Manifest V3 or later since Chrome 111. */ + export function clearComposition(parameters: ClearCompositionParameters): Promise; export function clearComposition( parameters: ClearCompositionParameters, - callback?: (success: boolean) => void, + callback: (success: boolean) => void, ): void; + /** * Set the position of the cursor in the candidate window. This is a no-op if this extension does not own the active IME. - * @param callback Called when the operation completes + * + * Can return its result via Promise in Manifest V3 or later since Chrome 111. */ export function setCursorPosition( parameters: CursorPositionParameters, - callback?: (success: boolean) => void, + ): Promise; + export function setCursorPosition( + parameters: CursorPositionParameters, + callback: (success: boolean) => void, ): void; + /** * Sends the key events. This function is expected to be used by virtual keyboards. When key(s) on a virtual keyboard is pressed by a user, this function is used to propagate that event to the system. - * @since Chrome 33 - * @param callback Called when the operation completes. - */ - export function sendKeyEvents(parameters: SendKeyEventParameters, callback?: () => void): void; - /** - * Hides the input view window, which is popped up automatically by system. If the input view window is already hidden, this function will do nothing. - * @since Chrome 34 + * + * Can return its result via Promise in Manifest V3 or later since Chrome 111. */ + export function sendKeyEvents(parameters: SendKeyEventParameters): Promise; + export function sendKeyEvents(parameters: SendKeyEventParameters, callback: () => void): void; + + /** Hides the input view window, which is popped up automatically by system. If the input view window is already hidden, this function will do nothing. */ export function hideInputView(): void; + /** * Deletes the text around the caret. - * @since Chrome 27 + * + * Can return its result via Promise in Manifest V3 or later since Chrome 111. */ - export function deleteSurroundingText(parameters: DeleteSurroundingTextParameters, callback?: () => void): void; + export function deleteSurroundingText(parameters: DeleteSurroundingTextParameters): Promise; + export function deleteSurroundingText(parameters: DeleteSurroundingTextParameters, callback: () => void): void; + /** * Indicates that the key event received by onKeyEvent is handled. This should only be called if the onKeyEvent listener is asynchronous. - * @since Chrome 25 * @param requestId Request id of the event that was handled. This should come from keyEvent.requestId * @param response True if the keystroke was handled, false if not */ export function keyEventHandled(requestId: string, response: boolean): void; /** This event is sent when focus leaves a text box. It is sent to all extensions that are listening to this event, and enabled by the user. */ - export var onBlur: BlurEvent; - /** This event is sent when a button in an assistive window is clicked. */ - export var onAssistiveWindowButtonClicked: AssistiveWindowButtonClickedEvent; + export const onBlur: events.Event<(contextID: number) => void>; + + /** + * This event is sent when a button in an assistive window is clicked. + * @since Chrome 85 + */ + export const onAssistiveWindowButtonClicked: events.Event< + (details: AssistiveWindowButtonClickedDetails) => void + >; + /** This event is sent if this extension owns the active IME. */ - export var onCandidateClicked: CandidateClickedEvent; - /** This event is sent if this extension owns the active IME. */ - export var onKeyEvent: KeyEventEvent; + export const onCandidateClicked: events.Event< + (engineID: string, candidateID: number, button: `${MouseButton}`) => void + >; + + /** Fired when a key event is sent from the operating system. The event will be sent to the extension if this extension owns the active IME. The listener function should return true if the event was handled false if it was not. If the event will be evaluated asynchronously, this function must return undefined and the IME must later call keyEventHandled() with the result. */ + export const onKeyEvent: events.Event<(engineID: string, keyData: KeyboardEvent, requestId: string) => void>; + /** This event is sent when an IME is deactivated. It signals that the IME will no longer be receiving onKeyPress events. */ - export var onDeactivated: DeactivatedEvent; - /** This event is sent when the properties of the current InputContext change, such as the type. It is sent to all extensions that are listening to this event, and enabled by the user. */ - export var onInputContextUpdate: InputContextUpdateEvent; + export const onDeactivated: events.Event<(engineID: string) => void>; + + /** This event is sent when the properties of the current InputContext change, such as the the type. It is sent to all extensions that are listening to this event, and enabled by the user. */ + export const onInputContextUpdate: events.Event<(context: InputContext) => void>; + /** This event is sent when an IME is activated. It signals that the IME will be receiving onKeyPress events. */ - export var onActivate: ActivateEvent; - /** This event is sent when focus enters a text box. It is sent to all extensions that are listening to this event, and enabled by the user. */ - export var onFocus: FocusEvent; + export const onActivate: events.Event<(engineID: string, screen: `${ScreenType}`) => void>; + + // /** This event is sent when focus enters a text box. It is sent to all extensions that are listening to this event, and enabled by the user. */ + export const onFocus: events.Event<(context: InputContext) => void>; + /** Called when the user selects a menu item */ - export var onMenuItemActivated: MenuItemActivatedEvent; - /** - * Called when the editable string around caret is changed or when the caret position is moved. The text length is limited to 100 characters for each back and forth direction. - * @since Chrome 27 - */ - export var onSurroundingTextChanged: SurroundingTextChangedEvent; - /** - * This event is sent when chrome terminates ongoing text input session. - * @since Chrome 29 - */ - export var onReset: InputResetEvent; + export const onMenuItemActivated: events.Event<(engineID: string, name: string) => void>; + + /** Called when the editable string around caret is changed or when the caret position is moved. The text length is limited to 100 characters for each back and forth direction. */ + export const onSurroundingTextChanged: events.Event< + (engineID: string, surroundingInfo: SurroundingTextInfo) => void + >; + + /** This event is sent when chrome terminates ongoing text input session. */ + export const onReset: events.Event<(engineID: string) => void>; } //////////////////// @@ -6672,35 +6932,32 @@ export namespace Browser { * @since Chrome 44 */ export namespace instanceID { - export interface TokenRefreshEvent extends Browser.events.Event<() => void> {} - /** * Resets the app instance identifier and revokes all tokens associated with it. * - * The `deleteID()` method doesn't return any value, but can be used with a callback or asynchronously, - * with a Promise (MV3 only). + * Can return its result via Promise in Manifest V3 or later since Chrome 96. */ export function deleteID(): Promise; export function deleteID(callback: () => void): void; + /** Parameters for {@link deleteToken}. */ interface DeleteTokenParams { /** - * Identifies the entity that is authorized to access resources associated with this Instance ID. - * It can be a project ID from Google developer console. + * The authorized entity that is used to obtain the token. + * @since Chrome 46 */ authorizedEntity: string; /** - * Identifies authorized actions that the authorized entity can take. - * In other words, the scope that is used to obtain the token. - * E.g. for sending GCM messages, `GCM` scope should be used. + * The scope that is used to obtain the token. + * @since Chrome 46 */ scope: string; } + /** - * Revoked a granted token. + * Revokes a granted token. * - * The `deleteToken()` method doesn't return any value, but can be used with a callback or - * asynchronously, with a Promise (MV3 only). + * Can return its result via Promise in Manifest V3 or later since Chrome 96. */ export function deleteToken(deleteTokenParams: DeleteTokenParams): Promise; export function deleteToken( @@ -6711,8 +6968,8 @@ export namespace Browser { /** * Retrieves the time when the InstanceID has been generated. * + * Can return its result via Promise in Manifest V3 or later since Chrome 96. * @return The time when the Instance ID has been generated, represented in milliseconds since the epoch. - * It can return via a callback or asynchronously, with a Promise (MV3 only). */ export function getCreationTime(): Promise; export function getCreationTime(callback: (creationTime: number) => void): void; @@ -6721,29 +6978,40 @@ export namespace Browser { * Retrieves an identifier for the app instance. * The same ID will be returned as long as the application identity has not been revoked or expired. * - * @return An Instance ID assigned to the app instance. Can be returned by a callback or a Promise (MV3 only). + * Can return its result via Promise in Manifest V3 or later since Chrome 96. + * @return An Instance ID assigned to the app instance. */ export function getID(): Promise; export function getID(callback: (instanceID: string) => void): void; - interface GetTokenParams extends DeleteTokenParams { + /** Parameters for {@link getToken}. */ + interface GetTokenParams { /** - * Allows including a small number of string key/value pairs that will be associated with the token - * and may be used in processing the request. - * - * @deprecated Since Chrome 89. `options` are deprecated and will be ignored. + * Identifies the entity that is authorized to access resources associated with this Instance ID. It can be a project ID from Google developer console. + * @since Chrome 46 + */ + authorizedEntity: string; + /** + * Allows including a small number of string key/value pairs that will be associated with the token and may be used in processing the request. + * @deprecated since Chrome 89. `options` are deprecated and will be ignored. */ options?: { [key: string]: string }; + /** + * Identifies authorized actions that the authorized entity can take. E.g. for sending GCM messages, `GCM` scope should be used. + * @since Chrome 46 + */ + scope: string; } /** * Return a token that allows the authorized entity to access the service defined by scope. * - * @return A token assigned by the requested service. Can be returned by a callback or a Promise (MV3 only). + * Can return its result via Promise in Manifest V3 or later since Chrome 96. + * @return A token assigned by the requested service. */ export function getToken(getTokenParams: GetTokenParams): Promise; export function getToken(getTokenParams: GetTokenParams, callback: (token: string) => void): void; - export var onTokenRefresh: TokenRefreshEvent; + export const onTokenRefresh: events.Event<() => void>; } //////////////////// @@ -6757,22 +7025,48 @@ export namespace Browser { * @since Chrome 78 */ export namespace loginState { - export interface SessionStateChangedEvent extends Browser.events.Event<(sessionState: SessionState) => void> {} + export enum ProfileType { + /** Specifies that the extension is in the signin profile. */ + SIGNIN_PROFILE = "SIGNIN_PROFILE", + /** Specifies that the extension is in the user profile. */ + USER_PROFILE = "USER_PROFILE", + /** Specifies that the extension is in the lock screen profile. */ + LOCK_PROFILE = "LOCK_PROFILE", + } - /** Possible profile types. */ - export type ProfileType = "SIGNIN_PROFILE" | "USER_PROFILE"; + export enum SessionState { + /** Specifies that the session state is unknown. */ + UNKNOWN = "UNKNOWN", + /** Specifies that the user is in the out-of-box-experience screen. */ + IN_OOBE_SCREEN = "IN_OOBE_SCREEN", + /** Specifies that the user is in the login screen. */ + IN_LOGIN_SCREEN = "IN_LOGIN_SCREEN", + /** Specifies that the user is in the session. */ + IN_SESSION = "IN_SESSION", + /** Specifies that the user is in the lock screen. */ + IN_LOCK_SCREEN = "IN_LOCK_SCREEN", + /** Specifies that the device is in RMA mode, finalizing repairs. */ + IN_RMA_SCREEN = "IN_RMA_SCREEN", + } - /** Possible session states. */ - export type SessionState = "UNKNOWN" | "IN_OOBE_SCREEN" | "IN_LOGIN_SCREEN" | "IN_SESSION" | "IN_LOCK_SCREEN"; + /** + * Gets the type of the profile the extension is in. + * + * Can return its result via Promise in Manifest V3 or later since Chrome 96. + */ + export function getProfileType(): Promise<`${ProfileType}`>; + export function getProfileType(callback: (result: `${ProfileType}`) => void): void; - /** Gets the type of the profile the extension is in. */ - export function getProfileType(callback: (profileType: ProfileType) => void): void; + /** + * Gets the current session state. + * + * Can return its result via Promise in Manifest V3 or later since Chrome 96. + */ + export function getSessionState(): Promise<`${SessionState}`>; + export function getSessionState(callback: (sessionState: `${SessionState}`) => void): void; - /** Gets the current session state. */ - export function getSessionState(callback: (sessionState: SessionState) => void): void; - - /** Dispatched when the session state changes. sessionState is the new session state.*/ - export const onSessionStateChanged: SessionStateChangedEvent; + /** Dispatched when the session state changes. `sessionState` is the new session state.*/ + export const onSessionStateChanged: events.Event<(sessionState: `${SessionState}`) => void>; } //////////////////// @@ -6784,54 +7078,42 @@ export namespace Browser { * Permissions: "management" */ export namespace management { + /** + * A reason the item is disabled. + * @since Chrome 44 + */ + export enum ExtensionDisabledReason { + UNKNOWN = "unknown", + PERMISSIONS_INCREASE = "permissions_increase", + } + /** Information about an installed extension, app, or theme. */ export interface ExtensionInfo { - /** - * Optional. - * A reason the item is disabled. - * @since Chrome 17 - */ - disabledReason?: string | undefined; - /** Optional. The launch url (only present for apps). */ - appLaunchUrl?: string | undefined; - /** - * The description of this extension, app, or theme. - * @since Chrome 9 - */ + /** A reason the item is disabled. */ + disabledReason?: `${ExtensionDisabledReason}`; + /** The launch url (only present for apps). */ + appLaunchUrl?: string; + /** The description of this extension, app, or theme. */ description: string; - /** - * Returns a list of API based permissions. - * @since Chrome 9 - */ + /** Returns a list of API based permissions. */ permissions: string[]; - /** - * Optional. - * 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[] | undefined; - /** - * Returns a list of host based permissions. - * @since Chrome 9 - */ + /** 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 host based permissions. */ hostPermissions: string[]; /** Whether it is currently enabled or disabled. */ enabled: boolean; - /** - * Optional. - * The URL of the homepage of this extension, app, or theme. - * @since Chrome 11 - */ - homepageUrl?: string | undefined; - /** - * Whether this extension can be disabled or uninstalled by the user. - * @since Chrome 12 - */ + /** The URL of the homepage of this extension, app, or theme. */ + homepageUrl?: string; + /** Whether this extension can be disabled or uninstalled by the user. */ mayDisable: boolean; /** - * How the extension was installed. - * @since Chrome 22 + * Whether this extension can be enabled by the user. This is only returned for extensions which are not enabled. + * @since Chrome 62 */ - installType: string; + mayEnable?: boolean; + /** How the extension was installed. */ + installType: `${ExtensionInstallType}`; /** The version of this extension, app, or theme. */ version: string; /** @@ -6841,266 +7123,217 @@ export namespace Browser { versionName?: string; /** The extension's unique identifier. */ id: string; - /** - * Whether the extension, app, or theme declares that it supports offline. - * @since Chrome 15 - */ + /** Whether the extension, app, or theme declares that it supports offline. */ offlineEnabled: boolean; - /** - * Optional. - * The update URL of this extension, app, or theme. - * @since Chrome 16 - */ - updateUrl?: string | undefined; - /** - * The type of this extension, app, or theme. - * @since Chrome 23 - */ - type: string; + /** The update URL of this extension, app, or theme. */ + updateUrl?: string; + /** The type of this extension, app, or theme. */ + type: `${ExtensionType}`; /** The url for the item's options page, if it has one. */ optionsUrl: string; /** The name of this extension, app, or theme. */ name: string; - /** - * A short version of the name of this extension, app, or theme. - * @since Chrome 31 - */ + /** A short version of the name of this extension, app, or theme. */ shortName: string; /** * True if this is an app. - * @deprecated since Chrome 33. Please use management.ExtensionInfo.type. + * @deprecated since Chrome 33. Please use {@link management.ExtensionInfo.type}. */ isApp: boolean; - /** - * Optional. - * The app launch type (only present for apps). - * @since Chrome 37 - */ - launchType?: string | undefined; - /** - * Optional. - * The currently available launch types (only present for apps). - * @since Chrome 37 - */ - availableLaunchTypes?: string[] | undefined; + /** The app launch type (only present for apps). */ + launchType?: `${LaunchType}`; + /** The currently available launch types (only present for apps). */ + availableLaunchTypes?: `${LaunchType}`[]; + } + + /** + * How the extension was installed + * @since Chrome 44 + */ + export enum ExtensionInstallType { + /** The extension was installed because of an administrative policy. */ + ADMIN = "admin", + /** The extension was loaded unpacked in developer mode. */ + DEVELOPMENT = "development", + /** The extension was installed normally via a .crx file. */ + NORMAL = "normal", + /** The extension was installed by other software on the machine. */ + SIDELOAD = "sideload", + /** The extension was installed by other means. */ + OTHER = "other", + } + + /** + * The type of this extension, app, or theme. + * @since Chrome 44 + */ + export enum ExtensionType { + EXTENSION = "extension", + HOSTED_APP = "hosted_app", + PACKAGE_APP = "package_app", + LEGACY_PACKAGED_APP = "legacy_packaged_app", + THEME = "theme", + LOGIN_SCREEN_EXTENSION = "login_screen_extension", } /** Information about an icon belonging to an extension, app, or theme. */ export interface IconInfo { - /** 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. */ + /** 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 number representing the width and height of the icon. Likely values include (but are not limited to) 128, 48, 24, and 16. */ size: number; } + /** These are all possible app launch types. */ + export enum LaunchType { + OPEN_AS_REGULAR_TAB = "OPEN_AS_REGULAR_TAB", + OPEN_AS_PINNED_TAB = "OPEN_AS_PINNED_TAB", + OPEN_AS_WINDOW = "OPEN_AS_WINDOW", + OPEN_FULL_SCREEN = "OPEN_FULL_SCREEN", + } + + /** + * Options for how to handle the extension's uninstallation. + * @since Chrome 88 + */ export interface UninstallOptions { - /** - * Optional. - * Whether or not a confirm-uninstall dialog should prompt the user. Defaults to false for self uninstalls. If an extension uninstalls another extension, this parameter is ignored and the dialog is always shown. - */ + /** Whether or not a confirm-uninstall dialog should prompt the user. Defaults to false for self uninstalls. If an extension uninstalls another extension, this parameter is ignored and the dialog is always shown. */ showConfirmDialog?: boolean | undefined; } - export interface ManagementDisabledEvent extends Browser.events.Event<(info: ExtensionInfo) => void> {} - - export interface ManagementUninstalledEvent extends Browser.events.Event<(id: string) => void> {} - - export interface ManagementInstalledEvent extends Browser.events.Event<(info: ExtensionInfo) => void> {} - - export interface ManagementEnabledEvent extends Browser.events.Event<(info: ExtensionInfo) => void> {} - /** - * Enables or disables an app or extension. - * @param id This should be the id from an item of management.ExtensionInfo. + * Enables or disables an app or extension. In most cases this function must be called in the context of a user gesture (e.g. an onclick handler for a button), and may present the user with a native confirmation UI as a way of preventing abuse. + * + * Can return its result via Promise in Manifest V3 or later since Chrome 88. + * @param id This should be the id from an item of {@link management.ExtensionInfo}. * @param enabled Whether this item should be enabled or disabled. - * @return The `setEnabled` method provides its result via callback or returned as a `Promise` (MV3 only). It has no parameters. */ export function setEnabled(id: string, enabled: boolean): Promise; - /** - * Enables or disables an app or extension. - * @param id This should be the id from an item of management.ExtensionInfo. - * @param enabled Whether this item should be enabled or disabled. - */ export function setEnabled(id: string, enabled: boolean, callback: () => void): void; + /** * Returns a list of permission warnings for the given extension id. - * @since Chrome 15 + * + * Can return its result via Promise in Manifest V3 or later since Chrome 88. * @param id The ID of an already installed extension. - * @return The `getPermissionWarningsById` method provides its result via callback or returned as a `Promise` (MV3 only). */ export function getPermissionWarningsById(id: string): Promise; - /** - * Returns a list of permission warnings for the given extension id. - * @since Chrome 15 - * @param id The ID of an already installed extension. - */ export function getPermissionWarningsById(id: string, callback: (permissionWarnings: string[]) => void): void; + /** * Returns information about the installed extension, app, or theme that has the given ID. - * @since Chrome 9 - * @param id The ID from an item of management.ExtensionInfo. - * @return The `get` method provides its result via callback or returned as a `Promise` (MV3 only). + * + * Can return its result via Promise in Manifest V3 or later since Chrome 88. + * @param id The ID from an item of {@link management.ExtensionInfo}. */ export function get(id: string): Promise; - /** - * Returns information about the installed extension, app, or theme that has the given ID. - * @since Chrome 9 - * @param id The ID from an item of management.ExtensionInfo. - */ export function get(id: string, callback: (result: ExtensionInfo) => void): void; + /** * Returns a list of information about installed extensions and apps. - * @return The `getAll` method provides its result via callback or returned as a `Promise` (MV3 only). + * + * Can return its result via Promise in Manifest V3 or later since Chrome 88. */ export function getAll(): Promise; - /** - * Returns a list of information about installed extensions and apps. - */ export function getAll(callback: (result: ExtensionInfo[]) => void): void; + /** * Returns a list of permission warnings for the given extension manifest string. Note: This function can be used without requesting the 'management' permission in the manifest. - * @since Chrome 15 - * @param manifestStr Extension manifest JSON string. - * @return The `getPermissionWarningsByManifest` method provides its result via callback or returned as a `Promise` (MV3 only). - */ - export function getPermissionWarningsByManifest( - manifestStr: string, - ): Promise; - /** - * Returns a list of permission warnings for the given extension manifest string. Note: This function can be used without requesting the 'management' permission in the manifest. - * @since Chrome 15 + * + * Can return its result via Promise in Manifest V3 or later since Chrome 88. * @param manifestStr Extension manifest JSON string. */ + export function getPermissionWarningsByManifest(manifestStr: string): Promise; export function getPermissionWarningsByManifest( manifestStr: string, - callback: (permissionwarnings: string[]) => void, + callback: (permissionWarnings: string[]) => void, ): void; + /** * Launches an application. + * + * Can return its result via Promise in Manifest V3 or later since Chrome 88. * @param id The extension id of the application. - * @return The `launchApp` method provides its result via callback or returned as a `Promise` (MV3 only). It has no parameters. */ export function launchApp(id: string): Promise; - /** - * Launches an application. - * @param id The extension id of the application. - */ export function launchApp(id: string, callback: () => void): void; + /** - * Uninstalls a currently installed app or extension. - * @since Chrome 21 - * @param id This should be the id from an item of management.ExtensionInfo. - * @return The `uninstall` method provides its result via callback or returned as a `Promise` (MV3 only). It has no parameters. + * Uninstalls a currently installed app or extension. Note: This function does not work in managed environments when the user is not allowed to uninstall the specified extension/app. If the uninstall fails (e.g. the user cancels the dialog) the promise will be rejected or the callback will be called with {@link runtime.lastError} set. + * + * Can return its result via Promise in Manifest V3 or later since Chrome 88. + * @param id This should be the id from an item of {@link management.ExtensionInfo}. */ export function uninstall(id: string, options?: UninstallOptions): Promise; - /** - * Uninstalls a currently installed app or extension. - * @since Chrome 21 - * @param id This should be the id from an item of management.ExtensionInfo. - */ - export function uninstall(id: string, callback: () => void): void; - export function uninstall(id: string, options: UninstallOptions, callback: () => void): void; - /** - * Uninstalls a currently installed app or extension. - * @deprecated since Chrome 21. The options parameter was added to this function. - * @param id This should be the id from an item of management.ExtensionInfo. - * @return The `uninstall` method provides its result via callback or returned as a `Promise` (MV3 only). It has no parameters. - */ - export function uninstall(id: string): Promise; - /** - * Uninstalls a currently installed app or extension. - * @deprecated since Chrome 21. The options parameter was added to this function. - * @param id This should be the id from an item of management.ExtensionInfo. - */ export function uninstall(id: string, callback: () => void): void; + export function uninstall(id: string, options: UninstallOptions | undefined, callback: () => void): void; + /** * Returns information about the calling extension, app, or theme. Note: This function can be used without requesting the 'management' permission in the manifest. - * @since Chrome 39 - * @return The `getSelf` method provides its result via callback or returned as a `Promise` (MV3 only). + * + * Can return its result via Promise in Manifest V3 or later since Chrome 88. */ export function getSelf(): Promise; - /** - * Returns information about the calling extension, app, or theme. Note: This function can be used without requesting the 'management' permission in the manifest. - * @since Chrome 39 - */ export function getSelf(callback: (result: ExtensionInfo) => void): void; + /** - * Uninstalls the calling extension. - * Note: This function can be used without requesting the 'management' permission in the manifest. - * @since Chrome 26 - * @return The `uninstallSelf` method provides its result via callback or returned as a `Promise` (MV3 only). It has no parameters. + * Launches the replacement_web_app specified in the manifest. Prompts the user to install if not already installed. + * + * Can return its result via Promise in Manifest V3 or later since Chrome 88. + * @since Chrome 77 + */ + export function installReplacementWebApp(): Promise; + export function installReplacementWebApp(callback: () => void): void; + + /** + * Uninstalls the calling extension. Note: This function can be used without requesting the 'management' permission in the manifest. This function does not work in managed environments when the user is not allowed to uninstall the specified extension/app. + * + * Can return its result via Promise in Manifest V3 or later since Chrome 88. */ export function uninstallSelf(options?: UninstallOptions): Promise; - /** - * Uninstalls the calling extension. - * Note: This function can be used without requesting the 'management' permission in the manifest. - * @since Chrome 26 - */ - export function uninstallSelf(callback: () => void): void; - export function uninstallSelf(options: UninstallOptions, callback: () => void): void; - /** - * Uninstalls the calling extension. - * Note: This function can be used without requesting the 'management' permission in the manifest. - * @since Chrome 26 - * @return The `uninstallSelf` method provides its result via callback or returned as a `Promise` (MV3 only). It has no parameters. - */ - export function uninstallSelf(): Promise; - /** - * Uninstalls the calling extension. - * Note: This function can be used without requesting the 'management' permission in the manifest. - * @since Chrome 26 - */ export function uninstallSelf(callback: () => void): void; + export function uninstallSelf(options: UninstallOptions | undefined, callback: () => void): void; + /** * Display options to create shortcuts for an app. On Mac, only packaged app shortcuts can be created. - * @since Chrome 37 - * @return The `createAppShortcut` method provides its result via callback or returned as a `Promise` (MV3 only). It has no parameters. + * + * Can return its result via Promise in Manifest V3 or later since Chrome 88. + * @param id This should be the id from an app item of {@link management.ExtensionInfo}. */ export function createAppShortcut(id: string): Promise; - /** - * Display options to create shortcuts for an app. On Mac, only packaged app shortcuts can be created. - * @since Chrome 37 - */ export function createAppShortcut(id: string, callback: () => void): void; + /** * Set the launch type of an app. - * @since Chrome 37 - * @param id This should be the id from an app item of management.ExtensionInfo. - * @param launchType The target launch type. Always check and make sure this launch type is in ExtensionInfo.availableLaunchTypes, because the available launch types vary on different platforms and configurations. - * @return The `setLaunchType` method provides its result via callback or returned as a `Promise` (MV3 only). It has no parameters. + * + * Can return its result via Promise in Manifest V3 or later since Chrome 88. + * @param id This should be the id from an app item of {@link management.ExtensionInfo}. + * @param launchType The target launch type. Always check and make sure this launch type is in {@link ExtensionInfo.availableLaunchTypes}, because the available launch types vary on different platforms and configurations. */ - export function setLaunchType(id: string, launchType: string): Promise; - /** - * Set the launch type of an app. - * @since Chrome 37 - * @param id This should be the id from an app item of management.ExtensionInfo. - * @param launchType The target launch type. Always check and make sure this launch type is in ExtensionInfo.availableLaunchTypes, because the available launch types vary on different platforms and configurations. - */ - export function setLaunchType(id: string, launchType: string, callback: () => void): void; + export function setLaunchType(id: string, launchType: `${LaunchType}`): Promise; + export function setLaunchType(id: string, launchType: `${LaunchType}`, callback: () => void): void; + /** * Generate an app for a URL. Returns the generated bookmark app. - * @since Chrome 37 + * + * Can return its result via Promise in Manifest V3 or later since Chrome 88. * @param url The URL of a web page. The scheme of the URL can only be "http" or "https". * @param title The title of the generated app. - * @return The `generateAppForLink` method provides its result via callback or returned as a `Promise` (MV3 only). */ export function generateAppForLink(url: string, title: string): Promise; - /** - * Generate an app for a URL. Returns the generated bookmark app. - * @since Chrome 37 - * @param url The URL of a web page. The scheme of the URL can only be "http" or "https". - * @param title The title of the generated app. - */ export function generateAppForLink(url: string, title: string, callback: (result: ExtensionInfo) => void): void; /** Fired when an app or extension has been disabled. */ - export var onDisabled: ManagementDisabledEvent; + export const onDisabled: events.Event<(info: ExtensionInfo) => void>; + /** Fired when an app or extension has been uninstalled. */ - export var onUninstalled: ManagementUninstalledEvent; + export const onUninstalled: events.Event<(id: string) => void>; + /** Fired when an app or extension has been installed. */ - export var onInstalled: ManagementInstalledEvent; + export const onInstalled: events.Event<(info: ExtensionInfo) => void>; + /** Fired when an app or extension has been enabled. */ - export var onEnabled: ManagementEnabledEvent; + export const onEnabled: events.Event<(info: ExtensionInfo) => void>; } //////////////////// @@ -7299,23 +7532,23 @@ export namespace Browser { export enum Reason { /** A reason used for testing purposes only. */ TESTING = "TESTING", - /** The offscreen document is responsible for playing audio. */ + /** Specifies that the offscreen document is responsible for playing audio. */ AUDIO_PLAYBACK = "AUDIO_PLAYBACK", - /** The offscreen document needs to embed and script an iframe in order to modify the iframe's content. */ + /** Specifies that the offscreen document needs to embed and script an iframe in order to modify the iframe's content. */ IFRAME_SCRIPTING = "IFRAME_SCRIPTING", - /** The offscreen document needs to embed an iframe and scrape its DOM to extract information. */ + /** Specifies that the offscreen document needs to embed an iframe and scrape its DOM to extract information. */ DOM_SCRAPING = "DOM_SCRAPING", - /** The offscreen document needs to interact with Blob objects (including URL.createObjectURL()). */ + /** Specifies that the offscreen document needs to interact with Blob objects (including `URL.createObjectURL()`). */ BLOBS = "BLOBS", - /** The offscreen document needs to use the DOMParser API. */ + /** Specifies that the offscreen document needs to use the DOMParser API. */ DOM_PARSER = "DOM_PARSER", - /** The offscreen document needs to interact with media streams from user media (e.g. getUserMedia()). */ + /** Specifies that the offscreen document needs to interact with media streams from user media (e.g. `getUserMedia()`). */ USER_MEDIA = "USER_MEDIA", - /** The offscreen document needs to interact with media streams from display media (e.g. getDisplayMedia()). */ + /** Specifies that the offscreen document needs to interact with media streams from display media (e.g. `getDisplayMedia()`). */ DISPLAY_MEDIA = "DISPLAY_MEDIA", - /** The offscreen document needs to use WebRTC APIs. */ + /** Specifies that the offscreen document needs to use WebRTC APIs. */ WEB_RTC = "WEB_RTC", - /** The offscreen document needs to interact with the clipboard APIs(e.g. Navigator.clipboard). */ + /** Specifies that the offscreen document needs to interact with the Clipboard API. */ CLIPBOARD = "CLIPBOARD", /** Specifies that the offscreen document needs access to localStorage. */ LOCAL_STORAGE = "LOCAL_STORAGE", @@ -7329,7 +7562,6 @@ export namespace Browser { GEOLOCATION = "GEOLOCATION", } - /** The parameters describing the offscreen document to create. */ export interface CreateParameters { /** The reason(s) the extension is creating the offscreen document. */ reasons: `${Reason}`[]; @@ -7342,36 +7574,26 @@ export namespace Browser { /** * Creates a new offscreen document for the extension. * @param parameters The parameters describing the offscreen document to create. - * @return The `createDocument` method provides its result via callback or returned as a `Promise` (MV3 only). + * + * Can return its result via Promise in Manifest V3. */ export function createDocument(parameters: CreateParameters): Promise; - /** - * Creates a new offscreen document for the extension. - * @param parameters The parameters describing the offscreen document to create. - * @param callback Invoked when the offscreen document is created and has completed its initial page load. - */ export function createDocument(parameters: CreateParameters, callback: () => void): void; /** * Closes the currently-open offscreen document for the extension. - * @return The `closeDocument` method provides its result via callback or returned as a `Promise` (MV3 only). + * + * Can return its result via Promise in Manifest V3. */ export function closeDocument(): Promise; - /** - * Closes the currently-open offscreen document for the extension. - * @param callback Invoked when the offscreen document has been closed. - */ export function closeDocument(callback: () => void): void; /** * Determines whether the extension has an active document. - * @return The `hasDocument` method provides its result via callback or returned as a `Promise` (MV3 only). + * + * Can return its result via Promise in Manifest V3. */ export function hasDocument(): Promise; - /** - * Determines whether the extension has an active document. - * @param callback Invoked with the result of whether the extension has an active offscreen document. - */ export function hasDocument(callback: (result: boolean) => void): void; } @@ -7397,47 +7619,60 @@ export namespace Browser { deletable?: boolean | undefined; } - export interface Suggestion { + /** A suggest result. */ + export interface DefaultSuggestResult { /** The text that is displayed in the URL dropdown. Can contain XML-style markup for styling. The supported tags are 'url' (for a literal URL), 'match' (for highlighting text that matched what the user's query), and 'dim' (for dim helper text). The styles can be nested, eg. dimmed match. */ description: string; } - /** The window disposition for the omnibox query. This is the recommended context to display results. */ - export type OnInputEnteredDisposition = "currentTab" | "newForegroundTab" | "newBackgroundTab"; + /** + * The style type. + * @since Chrome 44 + */ + export enum DescriptionStyleType { + URL = "url", + MATCH = "match", + DIM = "dim", + } - export interface OmniboxInputEnteredEvent - extends Browser.events.Event<(text: string, disposition: OnInputEnteredDisposition) => void> - {} - - export interface OmniboxInputChangedEvent - extends Browser.events.Event<(text: string, suggest: (suggestResults: SuggestResult[]) => void) => void> - {} - - export interface OmniboxInputStartedEvent extends Browser.events.Event<() => void> {} - - export interface OmniboxInputCancelledEvent extends Browser.events.Event<() => void> {} - - export interface OmniboxSuggestionDeletedEvent extends Browser.events.Event<(text: string) => void> {} + /** + * The window disposition for the omnibox query. This is the recommended context to display results. For example, if the omnibox command is to navigate to a certain URL, a disposition of 'newForegroundTab' means the navigation should take place in a new selected tab. + * @since Chrome 44 + */ + export enum OnInputEnteredDisposition { + CURRENT_TAB = "currentTab", + NEW_FOREGROUND_TAB = "newForegroundTab", + NEW_BACKGROUND_TAB = "newBackgroundTab", + } /** * Sets the description and styling for the default suggestion. The default suggestion is the text that is displayed in the first suggestion row underneath the URL bar. + * + * Can return its result via Promise in Manifest V3 or later since Chrome 100 * @param suggestion A partial SuggestResult object, without the 'content' parameter. */ - export function setDefaultSuggestion(suggestion: Suggestion): void; + export function setDefaultSuggestion(suggestion: DefaultSuggestResult): Promise; + export function setDefaultSuggestion(suggestion: DefaultSuggestResult, callback: () => void): void; /** User has accepted what is typed into the omnibox. */ - export var onInputEntered: OmniboxInputEnteredEvent; + export const onInputEntered: events.Event<(text: string, disposition: `${OnInputEnteredDisposition}`) => void>; + /** User has changed what is typed into the omnibox. */ - export var onInputChanged: OmniboxInputChangedEvent; + export const onInputChanged: events.Event< + (text: string, suggest: (suggestResults: SuggestResult[]) => void) => void + >; + /** User has started a keyword input session by typing the extension's keyword. This is guaranteed to be sent exactly once per input session, and before any onInputChanged events. */ - export var onInputStarted: OmniboxInputStartedEvent; + export const onInputStarted: events.Event<() => void>; + /** User has ended the keyword input session without accepting the input. */ - export var onInputCancelled: OmniboxInputCancelledEvent; + export const onInputCancelled: events.Event<() => void>; + /** * User has deleted a suggested result * @since Chrome 63 */ - export var onDeleteSuggestion: OmniboxSuggestionDeletedEvent; + export const onDeleteSuggestion: events.Event<(text: string) => void>; } //////////////////// @@ -7451,8 +7686,6 @@ export namespace Browser { * MV2 only */ export namespace pageAction { - export interface PageActionClickedEvent extends Browser.events.Event<(tab: Browser.tabs.Tab) => void> {} - export interface TitleDetails { /** The id of the tab for which you want to modify the page action. */ tabId: number; @@ -7460,77 +7693,77 @@ export namespace Browser { title: string; } - export interface GetDetails { - /** Specify the tab to get the title from. */ + export interface TabDetails { + /** The ID of the tab to query state for. */ tabId: number; } export interface PopupDetails { /** The id of the tab for which you want to modify the page action. */ tabId: number; - /** The html file to show in a popup. If set to the empty string (''), no popup is shown. */ + /** The relative path to the HTML file to show in a popup. If set to the empty string (`''`), no popup is shown. */ popup: string; } - export interface IconDetails { - /** The id of the tab for which you want to modify the page action. */ - tabId: number; - /** - * Optional. - * @deprecated This argument is ignored. - */ - iconIndex?: number | undefined; - /** - * Optional. - * 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}' - */ - imageData?: ImageData | { [index: number]: ImageData } | undefined; - /** - * Optional. - * Either a relative image path or a dictionary {size -> relative image path} pointing to 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.path = foo' is equivalent to 'details.imageData = {'19': foo}' - */ - path?: string | { [index: string]: string } | undefined; - } + export type IconDetails = + & { + /** @deprecated This argument is ignored. */ + iconIndex?: number | undefined; + /** The id of the tab for which you want to modify the page action. */ + tabId: number; + } + & ( + | { + /** 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` \* n will be selected, where n is the size of the icon in the UI. At least one image must be specified. Note that 'details.imageData = foo' is equivalent to 'details.imageData = {'16': foo}' */ + imageData: ImageData | { [index: number]: ImageData }; + /** Either a relative image path or a dictionary {size -> relative image path} pointing to 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` \* n will be selected, where n is the size of the icon in the UI. At least one image must be specified. Note that 'details.path = foo' is equivalent to 'details.path = {'16': foo}' */ + path?: string | { [index: string]: string } | undefined; + } + | { + /** 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` \* n will be selected, where n is the size of the icon in the UI. At least one image must be specified. Note that 'details.imageData = foo' is equivalent to 'details.imageData = {'16': foo}' */ + imageData?: ImageData | { [index: number]: ImageData } | undefined; + /** Either a relative image path or a dictionary {size -> relative image path} pointing to 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` \* n will be selected, where n is the size of the icon in the UI. At least one image must be specified. Note that 'details.path = foo' is equivalent to 'details.path = {'16': foo}' */ + path: string | { [index: string]: string }; + } + ); + + /** + * Hides the page action. Hidden page actions still appear in the Chrome toolbar, but are grayed out. + * @param tabId The id of the tab for which you want to modify the page action. + * @param callback Since Chrome 67 + */ + export function hide(tabId: number, callback?: () => void): void; /** * Shows the page action. The page action is shown whenever the tab is selected. * @param tabId The id of the tab for which you want to modify the page action. - * @param callback Supported since Chrome 67 - */ - export function hide(tabId: number, callback?: () => void): void; - /** - * Shows the page action. The page action is shown whenever the tab is selected. - * @param tabId The id of the tab for which you want to modify the page action. - * @param callback Supported since Chrome 67 + * @param callback Since Chrome 67 */ export function show(tabId: number, callback?: () => void): void; + /** * Sets the title of the page action. This is displayed in a tooltip over the page action. - * @param callback Supported since Chrome 67 + * @param callback Since Chrome 67 */ export function setTitle(details: TitleDetails, callback?: () => void): void; + /** - * Sets the html document to be opened as a popup when the user clicks on the page action's icon. - * @param callback Supported since Chrome 67 + * Sets the HTML document to be opened as a popup when the user clicks on the page action's icon. + * @param callback Since Chrome 67 */ export function setPopup(details: PopupDetails, callback?: () => void): void; - /** - * Gets the title of the page action. - * @since Chrome 19 - */ - export function getTitle(details: GetDetails, callback: (result: string) => void): void; - /** - * Gets the html document set as the popup for this page action. - * @since Chrome 19 - */ - export function getPopup(details: GetDetails, callback: (result: string) => void): void; - /** - * Sets the icon for the page action. The icon can be specified either as the path to an image file or as the pixel data from a canvas element, or as dictionary of either one of those. Either the path or the imageData property must be specified. - */ + + /** Gets the title of the page action. */ + export function getTitle(details: TabDetails, callback: (result: string) => void): void; + + /** Gets the html document set as the popup for this page action. */ + export function getPopup(details: TabDetails, callback: (result: string) => void): void; + + /** Sets the icon for the page action. The icon can be specified either as the path to an image file or as the pixel data from a canvas element, or as dictionary of either one of those. Either the path or the imageData property must be specified. */ export function setIcon(details: IconDetails, callback?: () => void): void; /** Fired when a page action icon is clicked. This event will not fire if the page action has a popup. */ - export var onClicked: PageActionClickedEvent; + export const onClicked: events.Event<(tab: Browser.tabs.Tab) => void>; } //////////////////// @@ -7549,15 +7782,11 @@ export namespace Browser { /** * Saves the content of the tab with given id as MHTML. - * @param callback Called when the MHTML has been generated. - * Parameter mhtmlData: The MHTML data as a Blob. - */ - export function saveAsMHTML(details: SaveDetails, callback: (mhtmlData?: Blob) => void): void; - /** - * Saves the content of the tab with given id as MHTML. - * @since Chrome 116 MV3 + * + * Can return its result via Promise in Manifest V3 or later since Chrome 116. */ export function saveAsMHTML(details: SaveDetails): Promise; + export function saveAsMHTML(details: SaveDetails, callback: (mhtmlData?: Blob) => void): void; } //////////////////// @@ -7571,7 +7800,7 @@ export namespace Browser { /** The list of host permissions, including those specified in the `optional_permissions` or `permissions` keys in the manifest, and those associated with [Content Scripts](https://developer.chrome.com/docs/extensions/develop/concepts/content-scripts). */ origins?: string[]; /** List of named permissions (does not include hosts or origins). */ - permissions?: Browser.runtime.ManifestPermissions[]; + permissions?: Browser.runtime.ManifestPermission[]; } export interface AddHostAccessRequest { @@ -7803,13 +8032,25 @@ export namespace Browser { id: string; /** Printer's human readable name. */ name: string; - /** Optional. Printer's human readable description. */ + /** Printer's human readable description. */ description?: string | undefined; } + /** Error codes returned in response to {@link onPrintRequested} event. */ + export enum PrintError { + /** Specifies that the operation was completed successfully. */ + OK = "OK", + /** Specifies that a general failure occured. */ + FAILED = "FAILED", + /** Specifies that the print ticket is invalid. For example, the ticket is inconsistent with some capabilities, or the extension is not able to handle all settings from the ticket. */ + INVALID_TICKET = "INVALID_TICKET", + /** Specifies that the document is invalid. For example, data may be corrupted or the format is incompatible with the extension. */ + INVALID_DATA = "INVALID_DATA", + } + export interface PrinterCapabilities { /** Device capabilities in CDD format. */ - capabilities: any; + capabilities: { [key: string]: unknown }; } export interface PrintJob { @@ -7817,44 +8058,68 @@ export namespace Browser { printerId: string; /** The print job title. */ title: string; - /** Print ticket in CJT format. */ + /** Print ticket in CJT format. */ ticket: { [key: string]: unknown }; - /** The document content type. Supported formats are "application/pdf" and "image/pwg-raster". */ + /** The document content type. Supported formats are `application/pdf` and `image/pwg-raster`. */ contentType: string; - /** Blob containing the document data to print. Format must match |contentType|. */ + /** Blob containing the document data to print. Format must match `contentType`. */ document: Blob; } - export interface PrinterRequestedEvent - extends Browser.events.Event<(resultCallback: (printerInfo: PrinterInfo[]) => void) => void> - {} - - export interface PrinterInfoRequestedEvent - extends Browser.events.Event<(device: any, resultCallback: (printerInfo?: PrinterInfo) => void) => void> - {} - - export interface CapabilityRequestedEvent extends - Browser.events.Event< - (printerId: string, resultCallback: (capabilities: PrinterCapabilities) => void) => void - > - {} - - export interface PrintRequestedEvent - extends Browser.events.Event<(printJob: PrintJob, resultCallback: (result: string) => void) => void> - {} + /** from https://developer.chrome.com/docs/apps/reference/usb#type-Device */ + export interface Device { + /** An opaque ID for the USB device. It remains unchanged until the device is unplugged. */ + device: number; + /** + * The iManufacturer string read from the device, if available. + * @since Chrome 46 + */ + manufacturerName: string; + /** The product ID. */ + productId: number; + /** + * The iProduct string read from the device, if available. + * @since Chrome 46 + */ + productName: string; + /** + * The iSerialNumber string read from the device, if available. + * @since Chrome 46 + */ + serialNumber: string; + /** The device vendor ID. */ + vendorId: number; + /** + * The device version (bcdDevice field). + * @since Chrome 51 + */ + version: number; + } /** Event fired when print manager requests printers provided by extensions. */ - export var onGetPrintersRequested: PrinterRequestedEvent; + export const onGetPrintersRequested: events.Event< + (resultCallback: (printerInfo: PrinterInfo[]) => void) => void + >; + /** * Event fired when print manager requests information about a USB device that may be a printer. - * Note: An application should not rely on this event being fired more than once per device. If a connected device is supported it should be returned in the onGetPrintersRequested event. + * + * Note: An application should not rely on this event being fired more than once per device. If a connected device is supported it should be returned in the {@link onGetPrintersRequested} event. * @since Chrome 45 */ - export var onGetUsbPrinterInfoRequested: PrinterInfoRequestedEvent; + export const onGetUsbPrinterInfoRequested: events.Event< + (device: Device, resultCallback: (printerInfo?: PrinterInfo) => void) => void + >; + /** Event fired when print manager requests printer capabilities. */ - export var onGetCapabilityRequested: CapabilityRequestedEvent; + export const onGetCapabilityRequested: events.Event< + (printerId: string, resultCallback: (capabilities: PrinterCapabilities) => void) => void + >; + /** Event fired when print manager requests printing. */ - export var onPrintRequested: PrintRequestedEvent; + export const onPrintRequested: events.Event< + (printJob: PrintJob, resultCallback: (result: `${PrintError}`) => void) => void + >; } //////////////////// @@ -8324,58 +8589,74 @@ export namespace Browser { * Permissions: "proxy" */ export namespace proxy { + /** @since Chrome 54 */ + export enum Mode { + /** Never use a proxy */ + DIRECT = "direct", + /** Auto detect proxy settings */ + AUTO_DETECT = "auto_detect", + /** Use specified PAC script */ + PAC_SCRIPT = "pac_script", + /** Manually specify proxy servers */ + FIXED_SERVERS = "fixed_servers", + /** Use system proxy settings */ + SYSTEM = "system", + } + /** An object holding proxy auto-config information. Exactly one of the fields should be non-empty. */ export interface PacScript { - /** Optional. URL of the PAC file to be used. */ + /** URL of the PAC file to be used. */ url?: string | undefined; - /** Optional. If true, an invalid PAC script will prevent the network stack from falling back to direct connections. Defaults to false. */ + /** If true, an invalid PAC script will prevent the network stack from falling back to direct connections. Defaults to false. */ mandatory?: boolean | undefined; - /** Optional. A PAC script. */ + /** A PAC script. */ data?: string | undefined; } /** An object encapsulating a complete proxy configuration. */ export interface ProxyConfig { - /** Optional. The proxy rules describing this configuration. Use this for 'fixed_servers' mode. */ + /** The proxy rules describing this configuration. Use this for 'fixed_servers' mode. */ rules?: ProxyRules | undefined; - /** Optional. The proxy auto-config (PAC) script for this configuration. Use this for 'pac_script' mode. */ + /** The proxy auto-config (PAC) script for this configuration. Use this for 'pac_script' mode. */ pacScript?: PacScript | undefined; - /** - * 'direct' = Never use a proxy - * 'auto_detect' = Auto detect proxy settings - * 'pac_script' = Use specified PAC script - * 'fixed_servers' = Manually specify proxy servers - * 'system' = Use system proxy settings - */ - mode: string; + mode: `${Mode}`; } /** An object encapsulating a single proxy server's specification. */ export interface ProxyServer { - /** The URI of the proxy server. This must be an ASCII hostname (in Punycode format). IDNA is not supported, yet. */ + /** The hostname or IP address of the proxy server. Hostnames must be in ASCII (in Punycode format). IDNA is not supported, yet. */ host: string; - /** Optional. The scheme (protocol) of the proxy server itself. Defaults to 'http'. */ - scheme?: string | undefined; - /** Optional. The port of the proxy server. Defaults to a port that depends on the scheme. */ + /** The scheme (protocol) of the proxy server itself. Defaults to 'http'. */ + scheme?: `${Scheme}` | undefined; + /** The port of the proxy server. Defaults to a port that depends on the scheme. */ port?: number | undefined; } /** An object encapsulating the set of proxy rules for all protocols. Use either 'singleProxy' or (a subset of) 'proxyForHttp', 'proxyForHttps', 'proxyForFtp' and 'fallbackProxy'. */ export interface ProxyRules { - /** Optional. The proxy server to be used for FTP requests. */ + /** The proxy server to be used for FTP requests. */ proxyForFtp?: ProxyServer | undefined; - /** Optional. The proxy server to be used for HTTP requests. */ + /** The proxy server to be used for HTTP requests. */ proxyForHttp?: ProxyServer | undefined; - /** Optional. The proxy server to be used for everything else or if any of the specific proxyFor... is not specified. */ + /** The proxy server to be used for everything else or if any of the specific proxyFor... is not specified. */ fallbackProxy?: ProxyServer | undefined; - /** Optional. The proxy server to be used for all per-URL requests (that is http, https, and ftp). */ + /** The proxy server to be used for all per-URL requests (that is http, https, and ftp). */ singleProxy?: ProxyServer | undefined; - /** Optional. The proxy server to be used for HTTPS requests. */ + /** The proxy server to be used for HTTPS requests. */ proxyForHttps?: ProxyServer | undefined; - /** Optional. List of servers to connect to without a proxy server. */ + /** List of servers to connect to without a proxy server. */ bypassList?: string[] | undefined; } + /** @since Chrome 54 */ + export enum Scheme { + HTTP = "http", + HTTPS = "https", + QUIC = "quic", + SOCKS4 = "socks4", + SOCKS5 = "socks5", + } + export interface ErrorDetails { /** Additional details about the error such as a JavaScript runtime error. */ details: string; @@ -8385,11 +8666,11 @@ export namespace Browser { fatal: boolean; } - export interface ProxyErrorEvent extends Browser.events.Event<(details: ErrorDetails) => void> {} + /** Proxy settings to be used. The value of this setting is a ProxyConfig object. */ + export const settings: types.ChromeSetting; - export var settings: Browser.types.ChromeSetting; /** Notifies about proxy errors. */ - export var onProxyError: ProxyErrorEvent; + export const onProxyError: events.Event<(details: ErrorDetails) => void>; } //////////////////// @@ -8449,57 +8730,48 @@ export namespace Browser { /** * Adds an entry to the reading list if it does not exist. - * @since Chrome 120, MV3 + * + * Can return its result via Promise. * @param entry The entry to add to the reading list. - * @param callback */ export function addEntry(entry: AddEntryOptions): Promise; export function addEntry(entry: AddEntryOptions, callback: () => void): void; /** * Retrieves all entries that match the `QueryInfo` properties. Properties that are not provided will not be matched. - * @since Chrome 120, MV3 + * + * Can return its result via Promise. * @param info The properties to search for. - * @param callback */ export function query(info: QueryInfo): Promise; export function query(info: QueryInfo, callback: (entries: ReadingListEntry[]) => void): void; /** * Removes an entry from the reading list if it exists. - * @since Chrome 120, MV3 + * + * Can return its result via Promise. * @param info The entry to remove from the reading list. - * @param callback */ export function removeEntry(info: RemoveOptions): Promise; export function removeEntry(info: RemoveOptions, callback: () => void): void; /** * Updates a reading list entry if it exists. - * @since Chrome 120, MV3 + * + * Can return its result via Promise. * @param info The entry to update. - * @param callback */ export function updateEntry(info: UpdateEntryOptions): Promise; export function updateEntry(info: UpdateEntryOptions, callback: () => void): void; - /** - * Triggered when a ReadingListEntry is added to the reading list. - * @since Chrome 120, MV3 - */ - export const onEntryAdded: Browser.events.Event<(entry: ReadingListEntry) => void>; + /** Triggered when a `ReadingListEntry` is added to the reading list. */ + export const onEntryAdded: events.Event<(entry: ReadingListEntry) => void>; - /** - * Triggered when a ReadingListEntry is removed from the reading list. - * @since Chrome 120, MV3 - */ - export const onEntryRemoved: Browser.events.Event<(entry: ReadingListEntry) => void>; + /** Triggered when a `ReadingListEntry` is removed from the reading list. */ + export const onEntryRemoved: events.Event<(entry: ReadingListEntry) => void>; - /** - * Triggered when a ReadingListEntry is updated in the reading list. - * @since Chrome 120, MV3 - */ - export const onEntryUpdated: Browser.events.Event<(entry: ReadingListEntry) => void>; + /** Triggered when a `ReadingListEntry` is updated in the reading list. */ + export const onEntryUpdated: events.Event<(entry: ReadingListEntry) => void>; } //////////////////// @@ -8512,29 +8784,42 @@ export namespace Browser { * @since Chrome 87 */ export namespace search { - export type Disposition = "CURRENT_TAB" | "NEW_TAB" | "NEW_WINDOW"; - - export interface QueryInfo { - /** Location where search results should be displayed. CURRENT_TAB is the default. */ - disposition?: Disposition | undefined; - /** Location where search results should be displayed. tabIdcannot be used with disposition. */ - tabId?: number | undefined; - /** String to query with the default search provider. */ - text?: string | undefined; + export enum Disposition { + /** Specifies that the search results display in the calling tab or the tab from the active browser. */ + CURRENT_TAB = "CURRENT_TAB", + /** Specifies that the search results display in a new tab. */ + NEW_TAB = "NEW_TAB", + /** Specifies that the search results display in a new window. */ + NEW_WINDOW = "NEW_WINDOW", } - /** - * Used to query the default search provider. In case of an error, runtime.lastError will be set. - * @param options search configuration options. - */ - export function query(options: QueryInfo, callback: () => void): void; + export type QueryInfo = + & { + /** String to query with the default search provider. */ + text?: string | undefined; + } + & ( + | { + /** Location where search results should be displayed. `CURRENT_TAB` is the default. */ + disposition?: `${Disposition}` | undefined; + /** Location where search results should be displayed. `tabId` cannot be used with `disposition`. */ + tabId?: undefined; + } + | { + /** Location where search results should be displayed. `CURRENT_TAB` is the default. */ + disposition?: undefined; + /** Location where search results should be displayed. `tabId` cannot be used with `disposition`. */ + tabId?: number | undefined; + } + ); /** - * Used to query the default search provider. In case of an error, runtime.lastError will be set. - * @param options search configuration options. - * @return The `query` method provides its result via callback or returned as a `Promise` (MV3 only). It has no parameters. + * Used to query the default search provider. In case of an error, {@link runtime.lastError} will be set. + * + * Can return its result via Promise in Manifest V3 or later since Chrome 96. */ export function query(options: QueryInfo): Promise; + export function query(options: QueryInfo, callback: () => void): void; } //////////////////// @@ -8821,7 +9106,7 @@ export namespace Browser { } /** Source: https://developer.chrome.com/docs/extensions/reference/permissions-list */ - export type ManifestPermissions = + export type ManifestPermission = | "accessibilityFeatures.modify" | "accessibilityFeatures.read" | "activeTab" @@ -8905,9 +9190,14 @@ export namespace Browser { | "webRequestBlocking" | "webRequestAuthProvider"; + /** + * @deprecated Use `ManifestPermission` instead. + */ + export type ManifestPermissions = ManifestPermission; + /** Source : https://developer.chrome.com/docs/extensions/reference/api/permissions */ - export type ManifestOptionalPermissions = Exclude< - ManifestPermissions, + export type ManifestOptionalPermission = Exclude< + ManifestPermission, | "debugger" | "declarativeNetRequest" | "devtools" @@ -8922,6 +9212,11 @@ export namespace Browser { | "webAuthenticationProxy" >; + /** + * @deprecated Use `ManifestOptionalPermission` instead. + */ + export type ManifestOptionalPermissions = ManifestOptionalPermission; + export interface SearchProvider { name?: string | undefined; keyword?: string | undefined; @@ -9141,8 +9436,8 @@ export namespace Browser { } | undefined; content_security_policy?: string | undefined; - optional_permissions?: ManifestOptionalPermissions[] | string[] | undefined; - permissions?: ManifestPermissions[] | string[] | undefined; + optional_permissions?: (ManifestOptionalPermission | string)[] | undefined; + permissions?: (ManifestPermission | string)[] | undefined; web_accessible_resources?: string[] | undefined; } @@ -9177,10 +9472,21 @@ export namespace Browser { sandbox?: string; }; host_permissions?: string[] | undefined; - optional_permissions?: ManifestOptionalPermissions[] | undefined; + optional_permissions?: ManifestOptionalPermission[] | undefined; optional_host_permissions?: string[] | undefined; - permissions?: ManifestPermissions[] | undefined; - web_accessible_resources?: Array<{ resources: string[]; matches: string[] }> | undefined; + permissions?: ManifestPermission[] | undefined; + web_accessible_resources?: + | Array< + & { + resources: string[]; + use_dynamic_url?: boolean | undefined; + } + & ( + | { extension_ids: string[]; matches?: string[] | undefined } + | { matches: string[]; extension_ids?: string[] | undefined } + ) + > + | undefined; } export type Manifest = ManifestV2 | ManifestV3; @@ -9249,6 +9555,13 @@ export namespace Browser { */ export function getURL(path: string): string; + /** + * Returns the extension's version as declared in the manifest. + * @returns The extension's version. + * @since Chrome 143 + */ + export function getVersion(): string; + /** Reloads the app or extension. This method is not supported in kiosk mode. For kiosk mode, use {@link Browser.runtime.restart()} method. */ export function reload(): void; @@ -9671,25 +9984,16 @@ export namespace Browser { */ export namespace sessions { export interface Filter { - /** - * Optional. - * The maximum number of entries to be fetched in the requested list. Omit this parameter to fetch the maximum number of entries (sessions.MAX_SESSION_RESULTS). - */ + /** The maximum number of entries to be fetched in the requested list. Omit this parameter to fetch the maximum number of entries ({@link sessions.MAX_SESSION_RESULTS}). */ maxResults?: number | undefined; } export interface Session { /** The time when the window or tab was closed or modified, represented in seconds since the epoch. */ lastModified: number; - /** - * Optional. - * The tabs.Tab, if this entry describes a tab. Either this or sessions.Session.window will be set. - */ + /** The {@link tabs.Tab}, if this entry describes a tab. Either this or {@link sessions.Session.window} will be set. */ tab?: tabs.Tab | undefined; - /** - * Optional. - * The windows.Window, if this entry describes a window. Either this or sessions.Session.tab will be set. - */ + /** The {@link windows.Window}, if this entry describes a window. Either this or {@link sessions.Session.tab} will be set. */ window?: windows.Window | undefined; } @@ -9700,69 +10004,39 @@ export namespace Browser { sessions: Session[]; } - export interface SessionChangedEvent extends Browser.events.Event<() => void> {} - - /** The maximum number of sessions.Session that will be included in a requested list. */ - export var MAX_SESSION_RESULTS: number; + /** The maximum number of {@link sessions.Session} that will be included in a requested list. */ + export const MAX_SESSION_RESULTS: 25; /** * Gets the list of recently closed tabs and/or windows. - * @return The `getRecentlyClosed` method provides its result via callback or returned as a `Promise` (MV3 only). + * + * Can return its result via Promise in Manifest V3 or later since Chrome 96. */ export function getRecentlyClosed(filter?: Filter): Promise; - /** - * Gets the list of recently closed tabs and/or windows. - * @param callback - * Parameter sessions: The list of closed entries in reverse order that they were closed (the most recently closed tab or window will be at index 0). The entries may contain either tabs or windows. - */ - export function getRecentlyClosed(filter: Filter, callback: (sessions: Session[]) => void): void; - /** - * Gets the list of recently closed tabs and/or windows. - * @param callback - * Parameter sessions: The list of closed entries in reverse order that they were closed (the most recently closed tab or window will be at index 0). The entries may contain either tabs or windows. - */ export function getRecentlyClosed(callback: (sessions: Session[]) => void): void; + export function getRecentlyClosed(filter: Filter | undefined, callback: (sessions: Session[]) => void): void; + /** * Retrieves all devices with synced sessions. - * @return The `getDevices` method provides its result via callback or returned as a `Promise` (MV3 only). + * + * Can return its result via Promise in Manifest V3 or later since Chrome 96. */ export function getDevices(filter?: Filter): Promise; - /** - * Retrieves all devices with synced sessions. - * @param callback - * Parameter devices: The list of sessions.Device objects for each synced session, sorted in order from device with most recently modified session to device with least recently modified session. tabs.Tab objects are sorted by recency in the windows.Window of the sessions.Session objects. - */ - export function getDevices(filter: Filter, callback: (devices: Device[]) => void): void; - /** - * Retrieves all devices with synced sessions. - * @param callback - * Parameter devices: The list of sessions.Device objects for each synced session, sorted in order from device with most recently modified session to device with least recently modified session. tabs.Tab objects are sorted by recency in the windows.Window of the sessions.Session objects. - */ export function getDevices(callback: (devices: Device[]) => void): void; + export function getDevices(filter: Filter | undefined, callback: (devices: Device[]) => void): void; + /** - * Reopens a windows.Window or tabs.Tab. - * @param sessionId Optional. - * The windows.Window.sessionId, or tabs.Tab.sessionId to restore. If this parameter is not specified, the most recently closed session is restored. - * @return The `restore` method provides its result via callback or returned as a `Promise` (MV3 only). + * Reopens a {@link windows.Window} or {@link tabs.Tab}, with an optional callback to run when the entry has been restored. + * + * Can return its result via Promise in Manifest V3 or later since Chrome 96. + * @param sessionId The {@link windows.Window.sessionId}, or {@link tabs.Tab.sessionId} to restore. If this parameter is not specified, the most recently closed session is restored. */ export function restore(sessionId?: string): Promise; - /** - * Reopens a windows.Window or tabs.Tab, with an optional callback to run when the entry has been restored. - * @param sessionId Optional. - * The windows.Window.sessionId, or tabs.Tab.sessionId to restore. If this parameter is not specified, the most recently closed session is restored. - * @param callback Optional. - * Parameter restoredSession: A sessions.Session containing the restored windows.Window or tabs.Tab object. - */ - export function restore(sessionId: string, callback: (restoredSession: Session) => void): void; - /** - * Reopens a windows.Window or tabs.Tab, with an optional callback to run when the entry has been restored. - * @param callback Optional. - * Parameter restoredSession: A sessions.Session containing the restored windows.Window or tabs.Tab object. - */ export function restore(callback: (restoredSession: Session) => void): void; + export function restore(sessionId: string | undefined, callback: (restoredSession: Session) => void): void; /** Fired when recently closed tabs and/or windows are changed. This event does not monitor synced sessions changes. */ - export var onChanged: SessionChangedEvent; + export const onChanged: events.Event<() => void>; } //////////////////// @@ -9782,209 +10056,153 @@ export namespace Browser { export interface StorageArea { /** * Gets the amount of space (in bytes) being used by one or more items. - * @param keys Optional. 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. - * @return A Promise that resolves with a number - * @since MV3 + * @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. + * + * Can return its result via Promise in Manifest V3 or later since Chrome 95. */ getBytesInUse(keys?: keyof T | Array | null): Promise; - /** - * Gets the amount of space (in bytes) being used by one or more items. - * @param keys Optional. 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 callback Callback with the amount of space being used by storage, or on failure (in which case runtime.lastError will be set). - * Parameter bytesInUse: Amount of space being used in storage, in bytes. - */ + getBytesInUse(callback: (bytesInUse: number) => void): void; getBytesInUse( - keys: keyof T | Array | null, + keys: keyof T | Array | null | undefined, callback: (bytesInUse: number) => void, ): void; - /** - * Gets the amount of space (in bytes) being used by one or more items. - * @param callback Callback with the amount of space being used by storage, or on failure (in which case runtime.lastError will be set). - * Parameter bytesInUse: Amount of space being used in storage, in bytes. - */ - getBytesInUse(callback: (bytesInUse: number) => void): void; + /** * Removes all items from storage. - * @return A void Promise - * @since MV3 + * + * Can return its result via Promise in Manifest V3 or later since Chrome 95. */ clear(): Promise; - /** - * Removes all items from storage. - * @param callback Optional. - * Callback on success, or on failure (in which case runtime.lastError will be set). - */ clear(callback: () => void): void; + /** * 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). - * @return A void Promise - * @since MV3 + * @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). + * + * Can return its result via Promise in Manifest V3 or later since Chrome 95. */ set(items: Partial): 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). - * @param callback Optional. - * Callback on success, or on failure (in which case runtime.lastError will be set). - */ set(items: Partial, callback: () => void): void; + /** * Removes one or more items from storage. * @param keys A single key or a list of keys for items to remove. - * @param callback Optional. - * @return A void Promise - * @since MV3 + * + * Can return its result via Promise in Manifest V3 or later since Chrome 95. */ remove(keys: keyof T | Array): Promise; - /** - * Removes one or more items from storage. - * @param keys A single key or a list of keys for items to remove. - * @param callback Optional. - * Callback on success, or on failure (in which case runtime.lastError will be set). - */ remove(keys: keyof T | Array, callback: () => void): void; + /** * 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. - * An empty list or object will return an empty result object. Pass in null to get the entire contents of storage. - * @return A Promise that resolves with an object containing items - * @since MV3 + * @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. + * + * Can return its result via Promise in Manifest V3 or later since Chrome 95. */ - get( + get( keys?: NoInferX | Array> | Partial> | null, ): Promise; - /** - * 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. - * An empty list or object will return an empty result object. Pass in null to get the entire contents of storage. - * @param callback Callback with storage items, or on failure (in which case runtime.lastError will be set). - * Parameter items: Object with items in their key-value mappings. - */ - get( - keys: NoInferX | Array> | Partial> | null, + get(callback: (items: T) => void): void; + get( + keys: NoInferX | Array> | Partial> | null | undefined, callback: (items: T) => void, ): void; + /** - * Gets the entire contents of storage. - * @param callback Callback with storage items, or on failure (in which case runtime.lastError will be set). - * Parameter items: Object with items in their key-value mappings. - */ - get(callback: (items: T) => void): void; - /** - * Sets the desired access level for the storage area. By default, session storage is restricted to trusted contexts (extension pages and service workers), while managed, local, and sync storage allow access from both trusted and untrusted contexts. - * @param accessOptions An object containing an accessLevel key which contains the access level of the storage area. - * @return A void Promise. + * Sets the desired access level for the storage area. By default, session storage is restricted to trusted contexts (extension pages and service workers), while `managed`, `local`, and `sync` storage allow access from both trusted and untrusted contexts. + * @param accessOptions The access level of the storage area. + * + * Can return its result via Promise in Manifest V3 or later. * @since Chrome 102 */ - setAccessLevel(accessOptions: { accessLevel: AccessLevel }): Promise; - /** - * Sets the desired access level for the storage area. By default, session storage is restricted to trusted contexts (extension pages and service workers), while managed, local, and sync storage allow access from both trusted and untrusted contexts. - * @param accessOptions An object containing an accessLevel key which contains the access level of the storage area. - * @param callback Optional. - * @since Chrome 102 - */ - setAccessLevel(accessOptions: { accessLevel: AccessLevel }, callback: () => void): void; - /** - * Fired when one or more items change within this storage area. - * @param keys A single key to get, list of keys to get, or a dictionary specifying default values. - * An empty list or object will return an empty result object. Pass in null to get the entire contents of storage. - * @param callback Callback with storage items, or on failure (in which case runtime.lastError will be set). - * Parameter items: Object with items in their key-value mappings. - */ - onChanged: StorageAreaChangedEvent; + setAccessLevel(accessOptions: { accessLevel: `${AccessLevel}` }): Promise; + setAccessLevel(accessOptions: { accessLevel: `${AccessLevel}` }, callback: () => void): void; + + /** Fired when one or more items change. */ + onChanged: events.Event<(changes: { [key: string]: StorageChange }) => void>; + /** * Gets all keys from storage. - * @return A Promise that resolves with an array of keys. + * + * Can return its result via Promise in Manifest V3 or later. * @since Chrome 130 */ getKeys(): Promise; - /** - * Gets all keys from storage. - * @param callback Callback with storage keys. - * Parameter keys: Array of keys in storage. - * @since Chrome 130 - */ getKeys(callback: (keys: string[]) => void): void; } export interface StorageChange { - /** Optional. The new value of the item, if there is a new value. */ - newValue?: any; - /** Optional. 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?: unknown; + /** The old value of the item, if there was an old value. */ + oldValue?: unknown; } export 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; + /** 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 when using a callback, or a rejected Promise if using async/await. */ + QUOTA_BYTES: 10485760; } export interface SyncStorageArea extends StorageArea { - /** @deprecated since Chrome 40. The storage.sync API no longer has a sustained write operation quota. */ - MAX_SUSTAINED_WRITE_OPERATIONS_PER_MINUTE: number; - /** 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; + /** @deprecated The storage.sync API no longer has a sustained write operation quota. */ + MAX_SUSTAINED_WRITE_OPERATIONS_PER_MINUTE: 1000000; + /** 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 when using a callback, or when a Promise is rejected. */ + QUOTA_BYTES: 102400; + /** 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 when using a callback, or when a Promise is rejected. */ + QUOTA_BYTES_PER_ITEM: 8192; + /** 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 when using a callback, or when a Promise is rejected. */ + MAX_ITEMS: 512; /** - * 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. + * 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 when using a callback, or when a Promise is rejected. */ - MAX_WRITE_OPERATIONS_PER_HOUR: number; + MAX_WRITE_OPERATIONS_PER_HOUR: 1800; /** - * 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. - * @since Chrome 40 + * 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 when using a callback, or when a Promise is rejected. */ - MAX_WRITE_OPERATIONS_PER_MINUTE: number; + MAX_WRITE_OPERATIONS_PER_MINUTE: 120; } export interface SessionStorageArea extends StorageArea { - /** The maximum amount (in bytes) of data that can be stored in memory, as measured by estimating the dynamically allocated memory usage of every value and key. Updates that would cause this limit to be exceeded fail immediately and set runtime.lastError. */ - QUOTA_BYTES: number; + /** The maximum amount (in bytes) of data that can be stored in memory, as measured by estimating the dynamically allocated memory usage of every value and key. Updates that would cause this limit to be exceeded fail immediately and set runtime.lastError when using a callback, or when a Promise is rejected. */ + QUOTA_BYTES: 10485760; } - export interface StorageAreaChangedEvent - extends Browser.events.Event<(changes: { [key: string]: StorageChange }) => void> - {} - - export type AreaName = keyof Pick; - export interface StorageChangedEvent - extends Browser.events.Event<(changes: { [key: string]: StorageChange }, areaName: AreaName) => void> - {} - - export type AccessLevel = keyof typeof AccessLevel; - - /** The storage area's access level. */ - export var AccessLevel: { - TRUSTED_AND_UNTRUSTED_CONTEXTS: "TRUSTED_AND_UNTRUSTED_CONTEXTS"; - TRUSTED_CONTEXTS: "TRUSTED_CONTEXTS"; - }; - - /** Items in the local storage area are local to each machine. */ - export var local: LocalStorageArea; - /** Items in the sync storage area are synced using Chrome Sync. */ - export var sync: SyncStorageArea; + export type AreaName = "sync" | "local" | "managed" | "session"; /** - * Items in the managed storage area are set by the domain administrator, and are read-only for the extension; trying to modify this namespace results in an error. - * @since Chrome 33 - */ - export var managed: StorageArea; - - /** - * Items in the session storage area are stored in-memory and will not be persisted to disk. + * The storage area's access level. * @since Chrome 102 */ - export var session: SessionStorageArea; + export enum AccessLevel { + /** Specifies contexts originating from the extension itself. */ + TRUSTED_CONTEXTS = "TRUSTED_CONTEXTS", + /** Specifies contexts originating from outside the extension. */ + TRUSTED_AND_UNTRUSTED_CONTEXTS = "TRUSTED_AND_UNTRUSTED_CONTEXTS", + } + + /** Items in the `local` storage area are local to each machine. */ + export const local: LocalStorageArea; + + /** Items in the `sync` storage area are synced using Chrome Sync. */ + export const sync: SyncStorageArea; + + /** Items in the `managed` storage area are set by an enterprise policy configured by the domain administrator, and are read-only for the extension; trying to modify this namespace results in an error. For information on configuring a policy, see Manifest for storage areas. */ + export const managed: StorageArea; + + /** + * Items in the `session` storage area are stored in-memory and will not be persisted to disk. + * + * MV3 only + * @since Chrome 102 + */ + export const session: SessionStorageArea; /** Fired when one or more items change. */ - export var onChanged: StorageChangedEvent; + export const onChanged: events.Event<(changes: { [key: string]: StorageChange }, areaName: AreaName) => void>; } //////////////////// @@ -9996,7 +10214,7 @@ export namespace Browser { * Permissions: "system.cpu" */ export namespace system.cpu { - export interface ProcessorUsage { + export interface CpuTime { /** The cumulative time used by userspace programs on this processor. */ user: number; /** The cumulative time used by kernel programs on this processor. */ @@ -10007,9 +10225,13 @@ export namespace Browser { total: number; } + /** @deprecated Use {@link CpuTime} instead. */ + // eslint-disable-next-line @typescript-eslint/no-empty-interface + interface ProcessorUsage extends CpuTime {} + export interface ProcessorInfo { /** Cumulative usage info for this logical processor. */ - usage: ProcessorUsage; + usage: CpuTime; } export interface CpuInfo { @@ -10026,16 +10248,20 @@ export namespace Browser { features: string[]; /** Information about each logical processor. */ processors: ProcessorInfo[]; + /** + * List of CPU temperature readings from each thermal zone of the CPU. Temperatures are in degrees Celsius. + * @since Chrome 60 + */ + temperatures: number[]; } - /** Queries basic CPU information of the system. */ - export function getInfo(callback: (info: CpuInfo) => void): void; - /** * Queries basic CPU information of the system. - * @return The `getInfo` method provides its result via callback or returned as a `Promise` (MV3 only). + * + * Can return its result via Promise in Manifest V3 or later since Chrome 91. */ export function getInfo(): Promise; + export function getInfo(callback: (info: CpuInfo) => void): void; } //////////////////// @@ -10054,14 +10280,13 @@ export namespace Browser { availableCapacity: number; } - /** Get physical memory information. */ - export function getInfo(callback: (info: MemoryInfo) => void): void; - /** * Get physical memory information. - * @return The `getInfo` method provides its result via callback or returned as a `Promise` (MV3 only). + * + * Can return its result via Promise in Manifest V3 or later since Chrome 91. */ export function getInfo(): Promise; + export function getInfo(callback: (info: MemoryInfo) => void): void; } //////////////////// @@ -10073,69 +10298,74 @@ export namespace Browser { * Permissions: "system.storage" */ export namespace system.storage { + export enum EjectDeviceResultCode { + /** The ejection command is successful -- the application can prompt the user to remove the device. */ + SUCCESS = "success", + /** The device is in use by another application. The ejection did not succeed; the user should not remove the device until the other application is done with the device. */ + IN_USE = "in_use", + /** There is no such device known. */ + NO_SUCH_DEVICE = "no_such_device", + /** The ejection command failed. */ + FAILURE = "failure", + } + export interface StorageUnitInfo { /** The transient ID that uniquely identifies the storage device. This ID will be persistent within the same run of a single application. It will not be a persistent identifier between different runs of an application, or between different applications. */ id: string; /** The name of the storage unit. */ name: string; - /** - * The media type of the storage unit. - * fixed: The storage has fixed media, e.g. hard disk or SSD. - * removable: The storage is removable, e.g. USB flash drive. - * unknown: The storage type is unknown. - */ - type: string; + /** The media type of the storage unit. */ + type: `${StorageUnitType}`; /** The total amount of the storage space, in bytes. */ capacity: number; } - export interface StorageCapacityInfo { - /** A copied |id| of getAvailableCapacity function parameter |id|. */ + export enum StorageUnitType { + /** The storage has fixed media, e.g. hard disk or SSD. */ + FIXED = "fixed", + /** The storage is removable, e.g. USB flash drive. */ + REMOVABLE = "removable", + /** The storage type is unknown. */ + UNKNOWN = "unknown", + } + + export interface StorageAvailableCapacityInfo { + /** A copied `id` of getAvailableCapacity function parameter `id`. */ id: string; /** The available capacity of the storage device, in bytes. */ availableCapacity: number; } - export interface SystemStorageAttachedEvent extends Browser.events.Event<(info: StorageUnitInfo) => void> {} - - export interface SystemStorageDetachedEvent extends Browser.events.Event<(id: string) => void> {} - - /** Get the storage information from the system. The argument passed to the callback is an array of StorageUnitInfo objects. */ - export function getInfo(callback: (info: StorageUnitInfo[]) => void): void; /** * Get the storage information from the system. The argument passed to the callback is an array of StorageUnitInfo objects. - * @return The `getInfo` method provides its result via callback or returned as a `Promise` (MV3 only). + * + * Can return its result via Promise in Manifest V3 or later since Chrome 91. */ export function getInfo(): Promise; + export function getInfo(callback: (info: StorageUnitInfo[]) => void): void; + /** * Ejects a removable storage device. - * @param callback - * Parameter result: success: The ejection command is successful -- the application can prompt the user to remove the device; in_use: The device is in use by another application. The ejection did not succeed; the user should not remove the device until the other application is done with the device; no_such_device: There is no such device known. failure: The ejection command failed. + * + * Can return its result via Promise in Manifest V3 or later since Chrome 91. */ - export function ejectDevice(id: string, callback: (result: string) => void): void; + export function ejectDevice(id: string): Promise<`${EjectDeviceResultCode}`>; + export function ejectDevice(id: string, callback: (result: `${EjectDeviceResultCode}`) => void): void; + /** - * Ejects a removable storage device. - * @param callback - * Parameter result: success: The ejection command is successful -- the application can prompt the user to remove the device; in_use: The device is in use by another application. The ejection did not succeed; the user should not remove the device until the other application is done with the device; no_such_device: There is no such device known. failure: The ejection command failed. - * @return The `ejectDevice` method provides its result via callback or returned as a `Promise` (MV3 only). - */ - export function ejectDevice(id: string): Promise; - /** - * Get the available capacity of a specified |id| storage device. The |id| is the transient device ID from StorageUnitInfo. + * Get the available capacity of a specified `id` storage device. The `id` is the transient device ID from StorageUnitInfo. + * + * Can return its result via Promise in Manifest V3. * @since Dev channel only. */ - export function getAvailableCapacity(id: string, callback: (info: StorageCapacityInfo) => void): void; - /** - * Get the available capacity of a specified |id| storage device. The |id| is the transient device ID from StorageUnitInfo. - * @since Dev channel only. - * @return The `getAvailableCapacity` method provides its result via callback or returned as a `Promise` (MV3 only). - */ - export function getAvailableCapacity(id: string): Promise; + export function getAvailableCapacity(id: string): Promise; + export function getAvailableCapacity(id: string, callback: (info: StorageAvailableCapacityInfo) => void): void; /** Fired when a new removable storage is attached to the system. */ - export var onAttached: SystemStorageAttachedEvent; + export const onAttached: events.Event<(info: StorageUnitInfo) => void>; + /** Fired when a removable storage is detached from the system. */ - export var onDetached: SystemStorageDetachedEvent; + export const onDetached: events.Event<(id: string) => void>; } //////////////////// @@ -10653,11 +10883,8 @@ export namespace Browser { export interface CaptureInfo { /** The id of the tab whose status changed. */ tabId: number; - /** - * The new capture status of the tab. - * One of: "pending", "active", "stopped", or "error" - */ - status: string; + /** The new capture status of the tab. */ + status: `${TabCaptureState}`; /** Whether an element in the tab being captured is in fullscreen mode. */ fullscreen: boolean; } @@ -10668,46 +10895,55 @@ export namespace Browser { } export interface CaptureOptions { - /** Optional. */ audio?: boolean | undefined; - /** Optional. */ video?: boolean | undefined; - /** Optional. */ audioConstraints?: MediaStreamConstraint | undefined; - /** Optional. */ videoConstraints?: MediaStreamConstraint | undefined; } + /** @since Chrome 71 */ export interface GetMediaStreamOptions { - /** Optional tab id of the tab which will later invoke getUserMedia() to consume the stream. If not specified then the resulting stream can be used only by the calling extension. The stream can only be used by frames in the given tab whose security origin matches the consumber tab's origin. The tab's origin must be a secure origin, e.g. HTTPS. */ + /** Optional tab id of the tab which will later invoke `getUserMedia()` to consume the stream. If not specified then the resulting stream can be used only by the calling extension. The stream can only be used by frames in the given tab whose security origin matches the consumber tab's origin. The tab's origin must be a secure origin, e.g. HTTPS. */ consumerTabId?: number | undefined; - /** Optional tab id of the tab which will be captured. If not specified then the current active tab will be selected. Only tabs for which the extension has been granted the activeTab permission can be used as the target tab. */ + /** Optional tab id of the tab which will be captured. If not specified then the current active tab will be selected. Only tabs for which the extension has been granted the `activeTab` permission can be used as the target tab. */ targetTabId?: number | undefined; } - export interface CaptureStatusChangedEvent extends Browser.events.Event<(info: CaptureInfo) => void> {} + export enum TabCaptureState { + PENDING = "pending", + ACTIVE = "active", + STOPPED = "stopped", + ERROR = "error", + } /** - * Captures the visible area of the currently active tab. Capture can only be started on the currently active tab after the extension has been invoked. Capture is maintained across page navigations within the tab, and stops when the tab is closed, or the media stream is closed by the extension. + * Captures the visible area of the currently active tab. Capture can only be started on the currently active tab after the extension has been invoked, similar to the way that activeTab works. Capture is maintained across page navigations within the tab, and stops when the tab is closed, or the media stream is closed by the extension. * @param options Configures the returned media stream. - * @param callback Callback with either the tab capture stream or null. */ export function capture(options: CaptureOptions, callback: (stream: MediaStream | null) => void): void; + /** * Returns a list of tabs that have requested capture or are being captured, i.e. status != stopped and status != error. This allows extensions to inform the user that there is an existing tab capture that would prevent a new tab capture from succeeding (or to prevent redundant requests for the same tab). - * @param callback Callback invoked with CaptureInfo[] for captured tabs. + * + * Can return its result via Promise in Manifest V3 or later since Chrome 116. */ + export function getCapturedTabs(): Promise; export function getCapturedTabs(callback: (result: CaptureInfo[]) => void): void; /** * Creates a stream ID to capture the target tab. Similar to Browser.tabCapture.capture() method, but returns a media stream ID, instead of a media stream, to the consumer tab. - * @param options Options for the media stream id to retrieve. - * @param callback Callback to invoke with the result. If successful, the result is an opaque string that can be passed to the getUserMedia() API to generate a media stream that corresponds to the target tab. The created streamId can only be used once and expires after a few seconds if it is not used. + * + * Can return its result via Promise in Manifest V3 or later since Chrome 116. */ - export function getMediaStreamId(options: GetMediaStreamOptions, callback: (streamId: string) => void): void; + export function getMediaStreamId(options?: GetMediaStreamOptions): Promise; + export function getMediaStreamId(callback: (streamId: string) => void): void; + export function getMediaStreamId( + options: GetMediaStreamOptions | undefined, + callback: (streamId: string) => void, + ): void; /** Event fired when the capture status of a tab changes. This allows extension authors to keep track of the capture status of tabs to keep UI elements like page actions in sync. */ - export var onStatusChanged: CaptureStatusChangedEvent; + export const onStatusChanged: events.Event<(info: CaptureInfo) => void>; } //////////////////// @@ -11033,6 +11269,11 @@ export namespace Browser { autoDiscardable?: boolean | undefined; /** Whether the tabs are pinned. */ pinned?: boolean | undefined; + /** + * The ID of the Split View that the tabs are in, or `tabs.SPLIT_VIEW_ID_NONE` for tabs that aren't in a Split View. + * @since Chrome 140 + */ + splitViewId?: number | undefined; /** * Whether the tabs are audible. * @since Chrome 45 @@ -11096,6 +11337,11 @@ export namespace Browser { mutedInfo?: MutedInfo; /** The tab's new pinned state. */ pinned?: boolean; + /** + * The tab's new Split View. + * @since Chrome 140 + */ + splitViewId?: number; /** The tab's loading status. */ status?: `${TabStatus}`; /** @@ -11718,7 +11964,7 @@ export namespace Browser { * Permissions: "topSites" */ export namespace topSites { - /** An object encapsulating a most visited URL, such as the URLs on the new tab page. */ + /** An object encapsulating a most visited URL, such as the default shortcuts on the new tab page. */ export interface MostVisitedURL { /** The most visited URL. */ url: string; @@ -11726,14 +11972,13 @@ export namespace Browser { title: string; } - /** Gets a list of top sites. */ - export function get(callback: (data: MostVisitedURL[]) => void): void; - /** * Gets a list of top sites. - * @return The `get` method provides its result via callback or returned as a `Promise` (MV3 only). + * + * Can return its result via Promise in Manifest V3 or later since Chrome 96. */ export function get(): Promise; + export function get(callback: (data: MostVisitedURL[]) => void): void; } //////////////////// @@ -12096,16 +12341,16 @@ export namespace Browser { */ value: T; /** Where to set the setting (default: regular). */ - scope?: ChromeSettingScope; + scope?: ChromeSettingScope | undefined; } /** Which setting to consider. */ export interface ChromeSettingGetDetails { /** Whether to return the value that applies to the incognito session (default false). */ - incognito?: boolean; + incognito?: boolean | undefined; } - /** Details of the currently effective value */ + /** Details of the currently effective value. */ export interface ChromeSettingGetResult { /** The level of control of the setting. */ levelOfControl: LevelOfControl; @@ -12113,7 +12358,7 @@ export namespace Browser { value: T; /** * 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. + * This property will only be present if the `incognito` property in the `details` parameter of `get()` was true. */ incognitoSpecific?: boolean; } @@ -12121,17 +12366,14 @@ export namespace Browser { /** Which setting to clear. */ export interface ChromeSettingClearDetails { /** Where to clear the setting (default: regular). */ - scope?: ChromeSettingScope; + scope?: ChromeSettingScope | undefined; } /** Details of the currently effective value. */ export interface ChromeSettingOnChangeDetails { - /** - * Whether the effective value is specific to the incognito session. T - * his property will only be present if the incognito property in the details parameter of get() was true. - */ + /** 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; - /** The value of the setting. */ + /** The value of the setting after the change. */ value: T; /** The level of control of the setting. */ levelOfControl: LevelOfControl; @@ -12144,27 +12386,30 @@ export namespace Browser { export interface ChromeSetting { /** * Sets the value of a setting. + * * Can return its result via Promise in Manifest V3 or later since Chrome 96. */ - set(details: ChromeSettingSetDetails, callback: () => void): void; set(details: ChromeSettingSetDetails): Promise; + set(details: ChromeSettingSetDetails, callback: () => void): void; /** * Gets the value of a setting. + * * Can return its result via Promise in Manifest V3 or later since Chrome 96. */ - get(details: ChromeSettingGetDetails, callback: (details: ChromeSettingGetResult) => void): void; get(details: ChromeSettingGetDetails): Promise>; + get(details: ChromeSettingGetDetails, callback: (details: ChromeSettingGetResult) => void): void; /** * Clears the setting, restoring any default value. + * * Can return its result via Promise in Manifest V3 or later since Chrome 96. */ - clear(details: ChromeSettingClearDetails, callback: () => void): void; clear(details: ChromeSettingClearDetails): Promise; + clear(details: ChromeSettingClearDetails, callback: () => void): void; /** Fired after the setting changes. */ - onChange: Browser.events.Event<(details: ChromeSettingOnChangeDetails) => void>; + onChange: events.Event<(details: ChromeSettingOnChangeDetails) => void>; } } @@ -12179,85 +12424,135 @@ export namespace Browser { * @since Chrome 43 */ export namespace vpnProvider { - export interface VpnSessionParameters { + export interface Parameters { /** IP address for the VPN interface in CIDR notation. IPv4 is currently the only supported mode. */ address: string; - /** Optional. Broadcast address for the VPN interface. (default: deduced from IP address and mask) */ + /** Broadcast address for the VPN interface. (default: deduced from IP address and mask) */ broadcastAddress?: string | undefined; - /** Optional. MTU setting for the VPN interface. (default: 1500 bytes) */ + /** MTU setting for the VPN interface. (default: 1500 bytes) */ mtu?: string | undefined; - /** - * Exclude network traffic to the list of IP blocks in CIDR notation from the tunnel. This can be used to bypass traffic to and from the VPN server. When many rules match a destination, the rule with the longest matching prefix wins. Entries that correspond to the same CIDR block are treated as duplicates. Such duplicates in the collated (exclusionList + inclusionList) list are eliminated and the exact duplicate entry that will be eliminated is undefined. - */ + /** Exclude network traffic to the list of IP blocks in CIDR notation from the tunnel. This can be used to bypass traffic to and from the VPN server. When many rules match a destination, the rule with the longest matching prefix wins. Entries that correspond to the same CIDR block are treated as duplicates. Such duplicates in the collated (exclusionList + inclusionList) list are eliminated and the exact duplicate entry that will be eliminated is undefined. */ exclusionList: string[]; - /** - * Include network traffic to the list of IP blocks in CIDR notation to the tunnel. This parameter can be used to set up a split tunnel. By default no traffic is directed to the tunnel. Adding the entry "0.0.0.0/0" to this list gets all the user traffic redirected to the tunnel. When many rules match a destination, the rule with the longest matching prefix wins. Entries that correspond to the same CIDR block are treated as duplicates. Such duplicates in the collated (exclusionList + inclusionList) list are eliminated and the exact duplicate entry that will be eliminated is undefined. - */ + /** Include network traffic to the list of IP blocks in CIDR notation to the tunnel. This parameter can be used to set up a split tunnel. By default no traffic is directed to the tunnel. Adding the entry "0.0.0.0/0" to this list gets all the user traffic redirected to the tunnel. When many rules match a destination, the rule with the longest matching prefix wins. Entries that correspond to the same CIDR block are treated as duplicates. Such duplicates in the collated (exclusionList + inclusionList) list are eliminated and the exact duplicate entry that will be eliminated is undefined. */ inclusionList: string[]; - /** Optional. A list of search domains. (default: no search domain) */ + /** A list of search domains. (default: no search domain) */ domainSearch?: string[] | undefined; /** A list of IPs for the DNS servers. */ - dnsServer: string[]; + dnsServers: string[]; + /** + * Whether or not the VPN extension implements auto-reconnection. + * + * If true, the `linkDown`, `linkUp`, `linkChanged`, `suspend`, and `resume` platform messages will be used to signal the respective events. If false, the system will forcibly disconnect the VPN if the network topology changes, and the user will need to reconnect manually. (default: false) + * + * This property is new in Chrome 51; it will generate an exception in earlier versions. try/catch can be used to conditionally enable the feature based on browser support. + * @since Chrome 51 + */ + reconnect?: string | undefined; } - export interface VpnPlatformMessageEvent - extends Browser.events.Event<(id: string, message: string, error: string) => void> - {} + /** @deprecated Use {@link Parameters} instead */ + // eslint-disable-next-line @typescript-eslint/no-empty-interface + interface VpnSessionParameters extends Parameters {} - export interface VpnPacketReceptionEvent extends Browser.events.Event<(data: ArrayBuffer) => void> {} + /** The enum is used by the platform to notify the client of the VPN session status. */ + export enum PlatformMessage { + /** Indicates that the VPN configuration connected. */ + CONNECTED = "connected", + /** Indicates that the VPN configuration disconnected. */ + DISCONNECTED = "disconnected", + /** Indicates that an error occurred in VPN connection, for example a timeout. A description of the error is given as the error argument to onPlatformMessage. */ + ERROR = "error", + /** Indicates that the default physical network connection is down. */ + LINK_DOWN = "linkDown", + /** Indicates that the default physical network connection is back up. */ + LINK_UP = "linkUp", + /** Indicates that the default physical network connection changed, e.g. wifi->mobile. */ + LINK_CHANGED = "linkChanged", + /** Indicates that the OS is preparing to suspend, so the VPN should drop its connection. The extension is not guaranteed to receive this event prior to suspending. */ + SUSPEND = "suspend", + /** Indicates that the OS has resumed and the user has logged back in, so the VPN should try to reconnect. */ + RESUME = "resume", + } - export interface VpnConfigRemovalEvent extends Browser.events.Event<(id: string) => void> {} + /** The enum is used by the platform to indicate the event that triggered {@link onUIEvent}. */ + export enum UIEvent { + /** Requests that the VPN client show the add configuration dialog box to the user. */ + SHOW_ADD_DIALOG = "showAddDialog", + /** Requests that the VPN client show the configuration settings dialog box to the user. */ + SHOW_CONFIGURE_DIALOG = "showConfigureDialog", + } - export interface VpnConfigCreationEvent - extends Browser.events.Event<(id: string, name: string, data: { [key: string]: unknown }) => void> - {} - - export interface VpnUiEvent extends Browser.events.Event<(event: string, id?: string) => void> {} + /** The enum is used by the VPN client to inform the platform of its current state. This helps provide meaningful messages to the user. */ + export enum VpnConnectionState { + /** Specifies that VPN connection was successful. */ + CONNECTED = "connected", + /** Specifies that VPN connection has failed. */ + FAILURE = "failure", + } /** * Creates a new VPN configuration that persists across multiple login sessions of the user. + * + * Can return its result via Promise in Manifest V3 or later since Chrome 96. * @param name The name of the VPN configuration. - * @param callback Called when the configuration is created or if there is an error. - * Parameter id: A unique ID for the created configuration, empty string on failure. */ + export function createConfig(name: string): Promise; export function createConfig(name: string, callback: (id: string) => void): void; + /** * Destroys a VPN configuration created by the extension. + * + * Can return its result via Promise in Manifest V3 or later since Chrome 96. * @param id ID of the VPN configuration to destroy. - * @param callback Optional. Called when the configuration is destroyed or if there is an error. */ - export function destroyConfig(id: string, callback?: () => void): void; + export function destroyConfig(id: string): Promise; + export function destroyConfig(id: string, callback: () => void): void; + /** - * Sets the parameters for the VPN session. This should be called immediately after "connected" is received from the platform. This will succeed only when the VPN session is owned by the extension. + * Sets the parameters for the VPN session. This should be called immediately after `"connected"` is received from the platform. This will succeed only when the VPN session is owned by the extension. + * + * Can return its result via Promise in Manifest V3 or later since Chrome 96. * @param parameters The parameters for the VPN session. - * @param callback Called when the parameters are set or if there is an error. */ - export function setParameters(parameters: VpnSessionParameters, callback?: () => void): void; + export function setParameters(parameters: Parameters): Promise; + export function setParameters(parameters: Parameters, callback: () => void): void; + /** * Sends an IP packet through the tunnel created for the VPN session. This will succeed only when the VPN session is owned by the extension. + * + * Can return its result via Promise in Manifest V3 or later since Chrome 96. * @param data The IP packet to be sent to the platform. - * @param callback Optional. Called when the packet is sent or if there is an error. */ - export function sendPacket(data: ArrayBuffer, callback?: () => void): void; + export function sendPacket(data: ArrayBuffer): Promise; + export function sendPacket(data: ArrayBuffer, callback: () => void): void; + /** * Notifies the VPN session state to the platform. This will succeed only when the VPN session is owned by the extension. + * + * Can return its result via Promise in Manifest V3 or later since Chrome 96. * @param state The VPN session state of the VPN client. - * connected: VPN connection was successful. - * failure: VPN connection failed. - * @param callback Optional. Called when the notification is complete or if there is an error. */ - export function notifyConnectionStateChanged(state: string, callback?: () => void): void; + export function notifyConnectionStateChanged(state: `${VpnConnectionState}`): Promise; + export function notifyConnectionStateChanged(state: `${VpnConnectionState}`, callback: () => void): void; /** Triggered when a message is received from the platform for a VPN configuration owned by the extension. */ - export var onPlatformMessage: VpnPlatformMessageEvent; + export const onPlatformMessage: events.Event< + (id: string, message: `${PlatformMessage}`, error: string) => void + >; + /** Triggered when an IP packet is received via the tunnel for the VPN session owned by the extension. */ - export var onPacketReceived: VpnPacketReceptionEvent; + export const onPacketReceived: events.Event<(data: ArrayBuffer) => void>; + /** Triggered when a configuration created by the extension is removed by the platform. */ - export var onConfigRemoved: VpnConfigRemovalEvent; - /** Triggered when a configuration is created by the platform for the extension. */ - export var onConfigCreated: VpnConfigCreationEvent; + export const onConfigRemoved: events.Event<(id: string) => void>; + + // /** Triggered when a configuration is created by the platform for the extension. */ + export const onConfigCreated: events.Event< + (id: string, name: string, data: { [key: string]: unknown }) => void + >; + /** Triggered when there is a UI event for the extension. UI events are signals from the platform that indicate to the app that a UI dialog needs to be shown to the user. */ - export var onUIEvent: VpnUiEvent; + export const onUIEvent: events.Event<(event: `${UIEvent}`, id?: string) => void>; } //////////////////// @@ -12271,27 +12566,35 @@ export namespace Browser { * @since Chrome 43 */ export namespace wallpaper { + /** + * The supported wallpaper layouts. + * @since Chrome 44 + */ + export enum WallpaperLayout { + STRETCH = "STRETCH", + CENTER = "CENTER", + CENTER_CROPPED = "CENTER_CROPPED", + } + export interface WallpaperDetails { - /** Optional. The jpeg or png encoded wallpaper image. */ + /** The jpeg or png encoded wallpaper image as an ArrayBuffer. */ data?: ArrayBuffer | undefined; - /** Optional. The URL of the wallpaper to be set. */ + /** The URL of the wallpaper to be set (can be relative). */ url?: string | undefined; - /** - * The supported wallpaper layouts. - * One of: "STRETCH", "CENTER", or "CENTER_CROPPED" - */ - layout: "STRETCH" | "CENTER" | "CENTER_CROPPED"; + /** The supported wallpaper layouts. */ + layout: `${WallpaperLayout}`; /** The file name of the saved wallpaper. */ filename: string; - /** Optional. True if a 128x60 thumbnail should be generated. */ + /** True if a 128x60 thumbnail should be generated. Layout and ratio are not supported yet. */ thumbnail?: boolean | undefined; } /** * Sets wallpaper to the image at url or wallpaperData with the specified layout - * @param callback - * Optional parameter thumbnail: The jpeg encoded wallpaper thumbnail. It is generated by resizing the wallpaper to 128x60. + * + * Can return its result via Promise in Manifest V3 or later since Chrome 96. */ + export function setWallpaper(details: WallpaperDetails): Promise; export function setWallpaper(details: WallpaperDetails, callback: (thumbnail?: ArrayBuffer) => void): void; } @@ -12421,33 +12724,84 @@ export namespace Browser { * Permissions: "webNavigation" */ export namespace webNavigation { - export interface GetFrameDetails { - /** - * The ID of the process runs the renderer for this tab. - * @since Chrome 22 - * @deprecated since Chrome 49. Frames are now uniquely identified by their tab ID and frame ID; the process ID is no longer needed and therefore ignored. - */ - processId?: number | undefined; - /** The ID of the tab in which the frame is. */ - tabId: number; - /** The ID of the frame in the given tab. */ - frameId: number; + /** @since Chrome 44 */ + export enum TransitionQualifier { + CLIENT_REDIRECT = "client_redirect", + SERVER_REDIRECT = "server_redirect", + FORWARD_BACK = "forward_back", + FROM_ADDRESS_BAR = "from_address_bar", } + /** + * 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). + * @since Chrome 44 + */ + export enum TransitionType { + LINK = "link", + TYPED = "typed", + AUTO_BOOKMARK = "auto_bookmark", + AUTO_SUBFRAME = "auto_subframe", + MANUAL_SUBFRAME = "manual_subframe", + GENERATED = "generated", + START_PAGE = "start_page", + FORM_SUBMIT = "form_submit", + RELOAD = "reload", + KEYWORD = "keyword", + KEYWORD_GENERATED = "keyword_generated", + } + + export type GetFrameDetails = + & ({ + /** + * The ID of the process that runs the renderer for this tab. + * @deprecated since Chrome 49. Frames are now uniquely identified by their tab ID and frame ID; the process ID is no longer needed and therefore ignored. + */ + processId?: number | undefined; + }) + & ( + { + /** The ID of the tab in which the frame is. */ + tabId?: number | undefined; + /** The ID of the frame in the given tab. */ + frameId?: number | undefined; + /** + * The UUID of the document. If the frameId and/or tabId are provided they will be validated to match the document found by provided document ID. + * @since Chrome 106 + */ + documentId: string; + } | { + /** The ID of the tab in which the frame is. */ + tabId: number; + /** The ID of the frame in the given tab. */ + frameId: number; + /** + * The UUID of the document. If the frameId and/or tabId are provided they will be validated to match the document found by provided document ID. + * @since Chrome 106 + */ + documentId?: string | undefined; + } + ); + export interface GetFrameResultDetails { /** The URL currently associated with this frame, if the frame identified by the frameId existed at one point in the given tab. The fact that an URL is associated with a given frameId does not imply that the corresponding frame still exists. */ url: string; /** A UUID of the document loaded. */ documentId: string; - /** The lifecycle the document is in. */ + /** + * The lifecycle the document is in. + * @since Chrome 106 + */ documentLifecycle: extensionTypes.DocumentLifecycle; /** True if the last navigation in this frame was interrupted by an error, i.e. the onErrorOccurred event fired. */ errorOccurred: boolean; /** The type of frame the navigation occurred in. */ frameType: extensionTypes.FrameType; - /** A UUID of the parent document owning this frame. This is not set if there is no parent. */ + /** + * A UUID of the parent document owning this frame. This is not set if there is no parent. + * @since Chrome 106 + */ parentDocumentId?: string | undefined; - /** ID of frame that wraps the frame. Set to -1 of no parent frame exists. */ + /** The ID of the parent frame, or `-1` if this is the main frame. */ parentFrameId: number; } @@ -12456,83 +12810,86 @@ export namespace Browser { tabId: number; } + /** A list of frames in the given tab, null if the specified tab ID is invalid. */ export interface GetAllFrameResultDetails extends GetFrameResultDetails { - /** The ID of the process runs the renderer for this tab. */ + /** The ID of the process that runs the renderer for this frame. */ processId: number; /** The ID of the frame. 0 indicates that this is the main frame; a positive value indicates the ID of a subframe. */ frameId: number; } - export interface WebNavigationCallbackDetails { - /** The ID of the tab in which the navigation is about to occur. */ + export interface WebNavigationReplacementCallbackDetails { + /** The ID of the tab that was replaced. */ + replacedTabId: number; + /** The ID of the tab that replaced the old tab. */ tabId: number; - /** The time when the browser was about to start the navigation, in milliseconds since the epoch. */ + /** The time when the replacement happened, in milliseconds since the epoch. */ timeStamp: number; } - export interface WebNavigationUrlCallbackDetails extends WebNavigationCallbackDetails { - url: string; - } - - export interface WebNavigationReplacementCallbackDetails extends WebNavigationCallbackDetails { - /** The ID of the tab that was replaced. */ - replacedTabId: number; - } - - export interface WebNavigationFramedCallbackDetails extends WebNavigationUrlCallbackDetails { - /** 0 indicates the navigation happens in the tab content window; a positive value indicates navigation in a subframe. Frame IDs are unique for a given tab and process. */ + export interface WebNavigationBaseCallbackDetails { + /** The lifecycle the document is in. */ + documentLifecycle: extensionTypes.DocumentLifecycle; + /** 0 indicates the navigation happens in the tab content window; a positive value indicates navigation in a subframe. Frame IDs are unique within a tab. */ frameId: number; /** The type of frame the navigation occurred in. */ frameType: extensionTypes.FrameType; - /** A UUID of the document loaded. (This is not set for onBeforeNavigate callbacks.) */ - documentId?: string | undefined; - /** The lifecycle the document is in. */ - documentLifecycle: extensionTypes.DocumentLifecycle; /** A UUID of the parent document owning this frame. This is not set if there is no parent. */ - parentDocumentId?: string | undefined; - /** - * The ID of the process runs the renderer for this tab. - * @since Chrome 22 - */ + parentDocumentId?: string; + /** The ID of the parent frame, or `-1` if this is the main frame. */ + parentFrameId: number; + /** The ID of the process that runs the renderer for this frame. */ processId: number; + /** The ID of the tab in which the navigation occurs. */ + tabId: number; + /** The time when the browser was about to start the navigation, in milliseconds since the epoch */ + timeStamp: number; + url: string; } - export interface WebNavigationFramedErrorCallbackDetails extends WebNavigationFramedCallbackDetails { + export interface WebNavigationFramedCallbackDetails extends WebNavigationBaseCallbackDetails { + /** + * A UUID of the document loaded. + * @since Chrome 106 + */ + documentId: string; + } + + export interface WebNavigationFramedErrorCallbackDetails extends WebNavigationBaseCallbackDetails { + /** + * A UUID of the document loaded. + * @since Chrome 106 + */ + documentId: string; /** The error description. */ error: string; } - export interface WebNavigationSourceCallbackDetails extends WebNavigationUrlCallbackDetails { - /** The ID of the tab in which the navigation is triggered. */ - sourceTabId: number; - /** - * The ID of the process runs the renderer for the source tab. - * @since Chrome 22 - */ - sourceProcessId: number; + export interface WebNavigationSourceCallbackDetails { /** The ID of the frame with sourceTabId in which the navigation is triggered. 0 indicates the main frame. */ sourceFrameId: number; + /** The ID of the process that runs the renderer for the source frame. */ + sourceProcessId: number; + /** The ID of the tab in which the navigation is triggered. */ + sourceTabId: number; + /** The ID of the tab in which the url is opened */ + tabId: number; + /** The time when the browser was about to create a new view, in milliseconds since the epoch. */ + timeStamp: number; + /** The URL to be opened in the new window. */ + url: string; } - export interface WebNavigationParentedCallbackDetails extends WebNavigationFramedCallbackDetails { + export interface WebNavigationTransitionCallbackDetails extends WebNavigationBaseCallbackDetails { /** - * ID of frame that wraps the frame. Set to -1 of no parent frame exists. - * @since Chrome 24 + * A UUID of the document loaded. + * @since Chrome 106 */ - parentFrameId: number; - } - - export interface WebNavigationTransitionCallbackDetails extends WebNavigationFramedCallbackDetails { - /** - * Cause of the navigation. - * One of: "link", "typed", "auto_bookmark", "auto_subframe", "manual_subframe", "generated", "start_page", "form_submit", "reload", "keyword", or "keyword_generated" - */ - transitionType: string; - /** - * A list of transition qualifiers. - * Each element one of: "client_redirect", "server_redirect", "forward_back", or "from_address_bar" - */ - transitionQualifiers: string[]; + documentId: string; + /** Cause of the navigation. */ + transitionType: `${TransitionType}`; + /** A list of transition qualifiers.*/ + transitionQualifiers: `${TransitionQualifier}`[]; } export interface WebNavigationEventFilter { @@ -12540,89 +12897,72 @@ export namespace Browser { url: Browser.events.UrlFilter[]; } - export interface WebNavigationEvent - extends Browser.events.Event<(details: T) => void> + interface WebNavigationEvent void> + extends Omit, "addListener"> { - addListener(callback: (details: T) => void, filters?: WebNavigationEventFilter): void; + addListener(callback: T, filters?: WebNavigationEventFilter): void; } - export interface WebNavigationFramedEvent extends WebNavigationEvent {} - - export interface WebNavigationFramedErrorEvent - extends WebNavigationEvent - {} - - export interface WebNavigationSourceEvent extends WebNavigationEvent {} - - export interface WebNavigationParentedEvent extends WebNavigationEvent {} - - export interface WebNavigationTransitionalEvent - extends WebNavigationEvent - {} - - export interface WebNavigationReplacementEvent - extends WebNavigationEvent - {} - /** * Retrieves information about the given frame. A frame refers to an