diff --git a/packages/browser/package.json b/packages/browser/package.json index 5beb97b92..5fdaccb84 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.0.323", + "version": "0.0.326", "type": "module", "main": "src/index.mjs", "types": "src/index.d.ts", @@ -23,9 +23,11 @@ "src" ], "devDependencies": { - "@types/chrome": "0.0.323", + "@types/chrome": "0.0.326", + "@types/firefox-webext-browser": "120.0.4", "fs-extra": "^11.3.0", "nano-spawn": "^0.2.0", + "ts-morph": "^26.0.0", "tsx": "4.19.4", "typescript": "^5.8.3", "vitest": "^3.1.2" diff --git a/packages/browser/scripts/generate.ts b/packages/browser/scripts/generate.ts index 0bde96c72..675c56531 100644 --- a/packages/browser/scripts/generate.ts +++ b/packages/browser/scripts/generate.ts @@ -3,11 +3,31 @@ import fs from 'fs-extra'; import { fileURLToPath } from 'node:url'; import { dirname, join, resolve, sep } from 'node:path'; import { sep as posixSep } from 'node:path/posix'; +import { + type FunctionDeclarationStructure, + type InterfaceDeclaration, + type ModuleDeclaration, + ModuleDeclarationKind, + Project, + StructureKind, + SyntaxKind, +} from 'ts-morph'; +import bcd, { + type Identifier, +} from '@mdn/browser-compat-data' with { type: 'json' }; // Fetch latest version -console.log('Getting latest version of \x1b[36m@types/chrome\x1b[0m'); -await spawn('pnpm', ['i', '--ignore-scripts', '-D', '@types/chrome@latest']); +console.log( + 'Getting latest version of \x1b[36m@types/chrome\x1b[0m, \x1b[36m@types/firefox-webext-browser\x1b[0m', +); +await spawn('pnpm', [ + 'i', + '--ignore-scripts', + '-D', + '@types/chrome@latest', + '@types/firefox-webext-browser@latest', +]); // Generate new package.json @@ -16,11 +36,18 @@ console.log('Generating new \x1b[36mpackage.json\x1b[0m'); const pkgJsonPath = fileURLToPath( import.meta.resolve('@types/chrome/package.json'), ); +const firefoxPkgJsonPath = fileURLToPath( + import.meta.resolve('@types/firefox-webext-browser/package.json'), +); const pkgDir = dirname(pkgJsonPath); +const firefoxPkgDir = dirname(firefoxPkgJsonPath); const pkgJson = await fs.readJson(pkgJsonPath); +const firefoxPkgJson = await fs.readJson(firefoxPkgJsonPath); const pkgJsonTemplate = await fs.readFile('templates/package.json', 'utf8'); const newPkgJson = JSON.parse( - pkgJsonTemplate.replaceAll('{{chromeTypesVersion}}', pkgJson.version), + pkgJsonTemplate + .replaceAll('{{chromeTypesVersion}}', pkgJson.version) + .replaceAll('{{firefoxTypesVersion}}', firefoxPkgJson.version), ); newPkgJson.dependencies = pkgJson.dependencies; newPkgJson.peerDependencies = pkgJson.peerDependencies; @@ -33,7 +60,209 @@ await spawn('pnpm', ['-w', 'prettier', '--write', outPkgJsonPath]); // Generate declaration files console.log('Generating declaration files'); + const outDir = resolve('src/gen'); + +const project = new Project({ + compilerOptions: { + declaration: true, + types: ['@types/chrome', '@types/firefox-webext-browser'], + baseUrl: outDir, + }, +}); +const chromeFile = resolve(pkgDir, 'index.d.ts'); +const firefoxFile = resolve(firefoxPkgDir, 'index.d.ts'); +const chrome = project.addSourceFileAtPath(chromeFile); +const firefox = project.addSourceFileAtPath(firefoxFile); + +const browserIndexFile = project.createSourceFile( + join(outDir, 'index.d.ts'), + `/* DO NOT EDIT - generated by scripts/generate.ts */ +${chrome + .getPathReferenceDirectives() + .map((file) => `/// `) + .join('\n')} +${chrome + .getTypeReferenceDirectives() + .map((file) => `/// `) + .join('\n')} + \n`, + { overwrite: true }, +); +const browserNamespace = browserIndexFile.addModule({ + name: 'Browser', + isExported: true, + kind: StructureKind.Module, + declarationKind: ModuleDeclarationKind.Namespace, +}); + +const browserExtensionCompatData = bcd.webextensions; +const browserInterface = browserIndexFile.addInterface({ + name: '_Browser', + isExported: true, + kind: StructureKind.Interface, +}); + +const modules: Record = {}; +const allModules = (chrome.getModule('chrome')?.getModules() || []).concat( + firefox?.getModules() || [], +); +allModules?.forEach((originalModule) => { + const moduleName = originalModule + .getName() + .replace(/^(browser\.|chrome\.)/, ''); + if (modules[moduleName]) { + const existingModule = modules[moduleName]; + existingModule.addInterfaces( + originalModule + .getInterfaces() + .filter((i) => !existingModule.getInterface(i.getName())) + .map((i) => i.getStructure()), + ); + existingModule.addClasses( + originalModule + .getClasses() + .filter((c) => !existingModule.getClass(c.getName() ?? 'NONE')) + .map((c) => c.getStructure()), + ); + existingModule.addFunctions( + originalModule + .getFunctions() + .filter((f) => !existingModule.getFunction(f.getName() ?? 'NONE')) + .map((f) => f.getStructure() as FunctionDeclarationStructure), + ); + existingModule.addVariableStatements( + originalModule + .getVariableStatements() + .filter( + (v) => + !existingModule.getVariableStatement( + v.getFirstChildByKind(SyntaxKind.Identifier)?.getText() ?? 'NONE', + ), + ) + .map((varDecl) => varDecl.getStructure()), + ); + } else { + const newModule = browserNamespace.addModule({ + ...originalModule.getStructure(), + name: moduleName, + isExported: true, + kind: StructureKind.Module, + declarationKind: ModuleDeclarationKind.Namespace, + }); + modules[moduleName] = newModule; + } + + const moduleCompatData = browserExtensionCompatData['api'][moduleName]; + if (moduleName.includes('.')) { + const moduleCompatApiData = browserExtensionCompatData['api']; + const [wrapperModuleName, innerModuleName] = moduleName.split('.'); + const nestedModuleCompatData = + moduleCompatApiData[wrapperModuleName]?.[innerModuleName] ?? {}; + + const compatData: Record = Object.fromEntries( + Object.entries(nestedModuleCompatData) + .map(([name, data]) => + Object.hasOwn(data, '__compat') + ? ([ + name, + !Object.entries( + (data as Identifier).__compat?.support ?? {}, + ).some(([, support]) => + Array.isArray(support) + ? support[0].version_added === false + : support.version_added === false, + ), + ] as const) + : [name, undefined], + ) + .filter(Boolean), + ); + const temporaryInterface = browserIndexFile.addInterface({ + name: '_' + moduleName.replace(/\./g, '_'), + isExported: true, + }); + + addFunction(originalModule, temporaryInterface, { + compatData, + name: innerModuleName, + }); + addVariable(originalModule, temporaryInterface, { + compatData, + name: innerModuleName, + }); + const temporaryInterfaceText = temporaryInterface.getText(); + const originalProperty = browserInterface.getProperty(wrapperModuleName); + if (originalProperty) { + const originalInterface = originalProperty.getTypeNodeOrThrow().getText(); + const newPropertyText = temporaryInterfaceText.slice( + temporaryInterfaceText.indexOf('{') + 1, + temporaryInterfaceText.lastIndexOf('}'), + ); + if (originalInterface.includes('}')) { + originalProperty.set({ + type: `${originalInterface.slice(0, originalInterface.lastIndexOf('}'))} ${newPropertyText}}`, + }); + } else { + originalProperty.set({ + type: `${originalInterface} & {${newPropertyText}}`, + }); + } + } else { + const newPropertyText = temporaryInterfaceText.slice( + temporaryInterfaceText.indexOf('{') + 1, + temporaryInterfaceText.lastIndexOf('}'), + ); + + browserInterface.addProperty({ + name: wrapperModuleName, + type: `{\n${newPropertyText}\n}`, + }); + } + + temporaryInterface.remove(); + return; + } + if (!moduleCompatData) { + browserInterface.addProperty({ + name: moduleName, + type: 'typeof Browser.' + moduleName, + hasQuestionToken: !moduleCompatData, + }); + } else { + const compatData: Record = Object.fromEntries( + Object.entries(moduleCompatData) + .map(([name, data]) => + Object.hasOwn(data, '__compat') + ? ([ + name, + !Object.entries( + (data as Identifier).__compat?.support ?? {}, + ).some(([, support]) => + Array.isArray(support) + ? support[0].version_added === false + : support.version_added === false, + ), + ] as const) + : [name, undefined], + ) + .filter(Boolean), + ); + addFunction(originalModule, browserInterface, { + compatData, + name: moduleName, + }); + addVariable(originalModule, browserInterface, { + compatData, + name: moduleName, + }); + } +}); + +browserInterface.formatText(); +await browserIndexFile.save(); + +// move Chrome declaration files to src/gen const declarationFileMapping = ( await fs.readdir(pkgDir, { recursive: true, @@ -41,7 +270,7 @@ const declarationFileMapping = ( }) ) // Filter to .d.ts files - .filter((file) => file.endsWith('.d.ts')) + .filter((file) => file.endsWith('.d.ts') && !file.startsWith('index.')) // Map to usable paths .map((file) => ({ file: file.replaceAll(sep, posixSep), @@ -51,13 +280,21 @@ const declarationFileMapping = ( for (const { file, srcPath, destPath } of declarationFileMapping) { const content = await fs.readFile(srcPath, 'utf8'); - const transformedContent = transformFile(file, content); const destDir = dirname(destPath); await fs.mkdir(destDir, { recursive: true }); - await fs.writeFile(destPath, transformedContent); + await fs.writeFile(destPath, content); console.log(` \x1b[2m-\x1b[0m \x1b[36m${file}\x1b[0m`); } +await fs.writeJson(outPkgJsonPath, newPkgJson); + +await spawn('pnpm', [ + '-w', + 'prettier', + '--write', + browserIndexFile.getFilePath(), +]); + // Done! console.log( @@ -66,17 +303,97 @@ console.log( // Transformations -function transformFile(file: string, content: string): string { - return ( - // Add prefix - `/* DO NOT EDIT - generated by scripts/generate.ts */\n\n${content}\n` - // Remove global type declaration - .replaceAll('chrome: typeof chrome;', '// chrome: typeof chrome;') - // Rename `chrome` namespace to `Browser` and export it - .replaceAll('declare namespace chrome', 'export namespace Browser') - // Update references to `chrome` namespace to `Browser` - .replaceAll('chrome.', 'Browser.') - // Fix links to developer.chrome.com - .replaceAll('developer.Browser.com', 'developer.chrome.com') - ); +function addFunction( + fromModule: ModuleDeclaration, + toInterface: InterfaceDeclaration, + options: { + name: string; + compatData: Record; + }, +) { + const moduleName = fromModule.getName().replace(/^(browser\.|chrome\.)/, ''); + const propertyEntries = fromModule.getFunctions().map((fn) => { + const fnName = fn.getNameOrThrow(); + return [fnName, options.compatData[fnName] === false]; + }); + const propertyText = Object.entries(Object.fromEntries(propertyEntries)) + .map(([name, optional]) => { + return `${name}${optional ? '?' : ''}: typeof Browser.${moduleName}.${name};`; + }) + .join('\n'); + const existingProperty = toInterface.getProperty(options.name); + if (propertyText.trim() === '') { + return; + } + if (existingProperty) { + const originalInterface = existingProperty.getText(); + const originalPropertyText = originalInterface.slice( + originalInterface.indexOf('{') + 1, + originalInterface.lastIndexOf('}'), + ); + + const propertyText = Object.entries(Object.fromEntries(propertyEntries)) + .filter(([name]) => !originalPropertyText.includes(name)) + .map(([name, optional]) => { + return `${name}${optional ? '?' : ''}: typeof Browser.${moduleName}.${name};`; + }) + .join('\n'); + existingProperty.set({ + type: `{\n${propertyText}${originalPropertyText.replace(' ', '')}\n}`, + }); + } else { + toInterface.addProperty({ + name: options.name, + type: `{\n${propertyText}\n}`, + }); + } +} +function addVariable( + fromModule: ModuleDeclaration, + toInterface: InterfaceDeclaration, + options: { + compatData: Record; + name: string; + }, +) { + const moduleName = fromModule.getName().replace(/^(browser\.|chrome\.)/, ''); + const propertyEntries = fromModule.getVariableDeclarations().map((fn) => { + const fnName = fn + .getFirstChildByKindOrThrow(SyntaxKind.Identifier) + .getText(); + return [fnName, options.compatData[fnName] === false]; + }); + + const existingProperty = toInterface.getProperty(options.name); + + if (existingProperty) { + const originalInterface = existingProperty.getText(); + const originalPropertyText = originalInterface.slice( + originalInterface.indexOf('{') + 1, + originalInterface.lastIndexOf('}'), + ); + + const propertyText = Object.entries(Object.fromEntries(propertyEntries)) + .filter(([name]) => !originalPropertyText.includes(name)) + .map(([name, optional]) => { + return `${name}${optional ? '?' : ''}: typeof Browser.${moduleName}.${name};`; + }) + .join('\n'); + existingProperty.set({ + type: `{\n${propertyText}${originalPropertyText.replace(' ', '')}\n}`, + }); + } else { + const propertyText = Object.entries(Object.fromEntries(propertyEntries)) + .map(([name, optional]) => { + return `${name}${optional ? '?' : ''}: typeof Browser.${moduleName}.${name};`; + }) + .join('\n'); + if (propertyText.trim() === '') { + return; + } + toInterface.addProperty({ + name: options.name, + type: `{\n${propertyText}\n}`, + }); + } } diff --git a/packages/browser/src/gen/chrome-cast/index.d.ts b/packages/browser/src/gen/chrome-cast/index.d.ts index 2b4ded948..7bca0f9dc 100644 --- a/packages/browser/src/gen/chrome-cast/index.d.ts +++ b/packages/browser/src/gen/chrome-cast/index.d.ts @@ -1,14 +1,12 @@ -/* DO NOT EDIT - generated by scripts/generate.ts */ - /* eslint-disable @typescript-eslint/no-wrapper-object-types */ -export namespace Browser { +declare namespace Browser { //////////////////// // Cast // @see https://code.google.com/p/chromium/codesearch#chromium/src/ui/file_manager/externs/chrome_cast.js //////////////////// export namespace cast { /** - * @see https://developers.google.com/cast/docs/reference/chrome/Browser.cast#.AutoJoinPolicy + * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast#.AutoJoinPolicy */ export enum AutoJoinPolicy { CUSTOM_CONTROLLER_SCOPED = "custom_controller_scoped", @@ -18,7 +16,7 @@ export namespace Browser { } /** - * @see https://developers.google.com/cast/docs/reference/chrome/Browser.cast#.DefaultActionPolicy + * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast#.DefaultActionPolicy */ export enum DefaultActionPolicy { CREATE_SESSION = "create_session", @@ -26,7 +24,7 @@ export namespace Browser { } /** - * @see https://developers.google.com/cast/docs/reference/chrome/Browser.cast#.Capability + * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast#.Capability */ export enum Capability { VIDEO_OUT = "video_out", @@ -37,7 +35,7 @@ export namespace Browser { } /** - * @see https://developers.google.com/cast/docs/reference/chrome/Browser.cast#.ErrorCode + * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast#.ErrorCode */ export enum ErrorCode { CANCEL = "cancel", @@ -53,7 +51,7 @@ export namespace Browser { } /** - * @see https://developers.google.com/cast/docs/reference/chrome/Browser.cast#.ReceiverAvailability + * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast#.ReceiverAvailability */ export enum ReceiverAvailability { AVAILABLE = "available", @@ -61,7 +59,7 @@ export namespace Browser { } /** - * @see https://developers.google.com/cast/docs/reference/chrome/Browser.cast#.SenderPlatform + * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast#.SenderPlatform */ export enum SenderPlatform { CHROME = "chrome", @@ -70,7 +68,7 @@ export namespace Browser { } /** - * @see https://developers.google.com/cast/docs/reference/chrome/Browser.cast#.ReceiverType + * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast#.ReceiverType */ export enum ReceiverType { CAST = "cast", @@ -80,7 +78,7 @@ export namespace Browser { } /** - * @see https://developers.google.com/cast/docs/reference/chrome/Browser.cast#.ReceiverAction + * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast#.ReceiverAction */ export enum ReceiverAction { CAST = "cast", @@ -88,7 +86,7 @@ export namespace Browser { } /** - * @see https://developers.google.com/cast/docs/reference/chrome/Browser.cast#.SessionStatus + * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast#.SessionStatus */ export enum SessionStatus { CONNECTED = "connected", @@ -97,12 +95,12 @@ export namespace Browser { } /** - * @see https://developers.google.com/cast/docs/reference/chrome/Browser.cast#.VERSION + * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast#.VERSION */ export var VERSION: number[]; /** - * @see https://developers.google.com/cast/docs/reference/chrome/Browser.cast#.isAvailable + * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast#.isAvailable */ export var isAvailable: boolean; @@ -178,7 +176,7 @@ export namespace Browser { /** * @param escaped A string to unescape. - * @see https://developers.google.com/cast/docs/reference/chrome/Browser.cast#.unescape + * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast#.unescape */ export function unescape(escaped: string): string; @@ -189,7 +187,7 @@ export namespace Browser { * @param receiverListener * @param opt_autoJoinPolicy * @param opt_defaultActionPolicy - * @see https://developers.google.com/cast/docs/reference/chrome/Browser.cast.ApiConfig + * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast.ApiConfig */ constructor( sessionRequest: Browser.cast.SessionRequest, @@ -211,7 +209,7 @@ export namespace Browser { * @param code * @param opt_description * @param opt_details - * @see https://developers.google.com/cast/docs/reference/chrome/Browser.cast.Error + * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast.Error */ constructor(code: Browser.cast.ErrorCode, description?: string, details?: Object); @@ -223,7 +221,7 @@ export namespace Browser { export class Image { /** * @param url - * @see https://developers.google.com/cast/docs/reference/chrome/Browser.cast.Image + * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast.Image */ constructor(url: string); @@ -235,7 +233,7 @@ export namespace Browser { export class SenderApplication { /** * @param platform - * @see https://developers.google.com/cast/docs/reference/chrome/Browser.cast.SenderApplication + * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast.SenderApplication */ constructor(platform: Browser.cast.SenderPlatform); @@ -249,7 +247,7 @@ export namespace Browser { * @param appId * @param opt_capabilities * @param opt_timeout - * @see https://developers.google.com/cast/docs/reference/chrome/Browser.cast.SessionRequest + * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast.SessionRequest */ constructor(appId: string, capabilities?: Browser.cast.Capability[], timeout?: number); @@ -266,7 +264,7 @@ export namespace Browser { * @param displayName * @param appImages * @param receiver - * @see https://developers.google.com/cast/docs/reference/chrome/Browser.cast.Session + * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast.Session */ constructor( sessionId: string, @@ -396,7 +394,7 @@ export namespace Browser { * @param friendlyName * @param opt_capabilities * @param opt_volume - * @see https://developers.google.com/cast/docs/reference/chrome/Browser.cast.Receiver + * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast.Receiver */ constructor( label: string, @@ -417,7 +415,7 @@ export namespace Browser { /** * @param statusText * @param appImages - * @see https://developers.google.com/cast/docs/reference/chrome/Browser.cast.ReceiverDisplayStatus + * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast.ReceiverDisplayStatus */ constructor(statusText: string, appImages: Browser.cast.Image[]); @@ -429,7 +427,7 @@ export namespace Browser { /** * @param opt_level * @param opt_muted - * @see https://developers.google.com/cast/docs/reference/chrome/Browser.cast.Volume + * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast.Volume */ constructor(level?: number, muted?: boolean); @@ -442,7 +440,7 @@ export namespace Browser { export var DEFAULT_MEDIA_RECEIVER_APP_ID: string; /** - * @see https://developers.google.com/cast/docs/reference/chrome/Browser.cast.media#.MediaCommand + * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast.media#.MediaCommand */ export enum MediaCommand { PAUSE = "pause", @@ -452,7 +450,7 @@ export namespace Browser { } /** - * @see https://developers.google.com/cast/docs/reference/chrome/Browser.cast.media#.MetadataType + * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast.media#.MetadataType */ export enum MetadataType { GENERIC, @@ -463,7 +461,7 @@ export namespace Browser { } /** - * @see https://developers.google.com/cast/docs/reference/chrome/Browser.cast.media#.PlayerState + * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast.media#.PlayerState */ export enum PlayerState { IDLE = "IDLE", @@ -473,7 +471,7 @@ export namespace Browser { } /** - * @see https://developers.google.com/cast/docs/reference/chrome/Browser.cast.media#.ResumeState + * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast.media#.ResumeState */ export enum ResumeState { PLAYBACK_START = "PLAYBACK_START", @@ -481,7 +479,7 @@ export namespace Browser { } /** - * @see https://developers.google.com/cast/docs/reference/chrome/Browser.cast.media#.StreamType + * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast.media#.StreamType */ export enum StreamType { BUFFERED = "BUFFERED", @@ -490,7 +488,7 @@ export namespace Browser { } /** - * @see https://developers.google.com/cast/docs/reference/chrome/Browser.cast.media#.IdleReason + * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast.media#.IdleReason */ export enum IdleReason { CANCELLED = "CANCELLED", @@ -500,7 +498,7 @@ export namespace Browser { } /** - * @see https://developers.google.com/cast/docs/reference/chrome/Browser.cast.media#.RepeatMode + * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast.media#.RepeatMode */ export enum RepeatMode { OFF = "REPEAT_OFF", @@ -512,7 +510,7 @@ export namespace Browser { export class QueueItem { /** * @param mediaInfo - * @see https://developers.google.com/cast/docs/reference/chrome/Browser.cast.media.QueueItem + * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast.media.QueueItem */ constructor(mediaInfo: Browser.cast.media.MediaInfo); @@ -528,7 +526,7 @@ export namespace Browser { export class QueueLoadRequest { /** * @param items - * @see https://developers.google.com/cast/docs/reference/chrome/Browser.cast.media.QueueLoadRequest + * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast.media.QueueLoadRequest */ constructor(items: Browser.cast.media.QueueItem[]); @@ -541,7 +539,7 @@ export namespace Browser { export class QueueInsertItemsRequest { /** * @param itemsToInsert - * @see https://developers.google.com/cast/docs/reference/chrome/Browser.cast.media.QueueInsertItemsRequest + * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast.media.QueueInsertItemsRequest */ constructor(itemsToInsert: Browser.cast.media.QueueItem[]); @@ -553,7 +551,7 @@ export namespace Browser { export class QueueRemoveItemsRequest { /** * @param itemIdsToRemove - * @see https://developers.google.com/cast/docs/reference/chrome/Browser.cast.media.QueueRemoveItemsRequest + * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast.media.QueueRemoveItemsRequest */ constructor(itemIdsToRemove: number[]); @@ -564,7 +562,7 @@ export namespace Browser { export class QueueReorderItemsRequest { /** * @param itemIdsToReorder - * @see https://developers.google.com/cast/docs/reference/chrome/Browser.cast.media.QueueReorderItemsRequest + * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast.media.QueueReorderItemsRequest */ constructor(itemIdsToReorder: number[]); @@ -576,7 +574,7 @@ export namespace Browser { export class QueueUpdateItemsRequest { /** * @param itemsToUpdate - * @see https://developers.google.com/cast/docs/reference/chrome/Browser.cast.media.QueueUpdateItemsRequest + * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast.media.QueueUpdateItemsRequest */ constructor(itemsToUpdate: Browser.cast.media.QueueItem[]); @@ -585,7 +583,7 @@ export namespace Browser { } /** - * @see https://developers.google.com/cast/docs/reference/chrome/Browser.cast.media#.TrackType + * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast.media#.TrackType */ export enum TrackType { TEXT = "TEXT", @@ -594,7 +592,7 @@ export namespace Browser { } /** - * @see https://developers.google.com/cast/docs/reference/chrome/Browser.cast.media#.TextTrackType + * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast.media#.TextTrackType */ export enum TextTrackType { SUBTITLES = "SUBTITLES", @@ -605,7 +603,7 @@ export namespace Browser { } /** - * @see https://developers.google.com/cast/docs/reference/chrome/Browser.cast.media#.TextTrackEdgeType + * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast.media#.TextTrackEdgeType */ export enum TextTrackEdgeType { NONE = "NONE", @@ -616,7 +614,7 @@ export namespace Browser { } /** - * @see https://developers.google.com/cast/docs/reference/chrome/Browser.cast.media#.TextTrackWindowType + * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast.media#.TextTrackWindowType */ export enum TextTrackWindowType { NONE = "NONE", @@ -625,7 +623,7 @@ export namespace Browser { } /** - * @see https://developers.google.com/cast/docs/reference/chrome/Browser.cast.media#.TextTrackFontGenericFamily + * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast.media#.TextTrackFontGenericFamily */ export enum TextTrackFontGenericFamily { SANS_SERIF = "SANS_SERIF", @@ -638,7 +636,7 @@ export namespace Browser { } /** - * @see https://developers.google.com/cast/docs/reference/chrome/Browser.cast.media#.TextTrackFontStyle + * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast.media#.TextTrackFontStyle */ export enum TextTrackFontStyle { NORMAL = "NORMAL", @@ -649,7 +647,7 @@ export namespace Browser { export class GetStatusRequest { /** - * @see https://developers.google.com/cast/docs/reference/chrome/Browser.cast.media.GetStatusRequest + * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast.media.GetStatusRequest */ constructor(); @@ -658,7 +656,7 @@ export namespace Browser { export class PauseRequest { /** - * @see https://developers.google.com/cast/docs/reference/chrome/Browser.cast.media.PauseRequest + * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast.media.PauseRequest */ constructor(); @@ -667,7 +665,7 @@ export namespace Browser { export class PlayRequest { /** - * @see https://developers.google.com/cast/docs/reference/chrome/Browser.cast.media.PlayRequest + * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast.media.PlayRequest */ constructor(); @@ -676,7 +674,7 @@ export namespace Browser { export class SeekRequest { /** - * @see https://developers.google.com/cast/docs/reference/chrome/Browser.cast.media.SeekRequest + * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast.media.SeekRequest */ constructor(); @@ -687,7 +685,7 @@ export namespace Browser { export class StopRequest { /** - * @see https://developers.google.com/cast/docs/reference/chrome/Browser.cast.media.StopRequest + * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast.media.StopRequest */ constructor(); @@ -697,7 +695,7 @@ export namespace Browser { export class VolumeRequest { /** * @param volume - * @see https://developers.google.com/cast/docs/reference/chrome/Browser.cast.media.VolumeRequest + * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast.media.VolumeRequest */ constructor(volume: Browser.cast.Volume); @@ -708,7 +706,7 @@ export namespace Browser { export class LoadRequest { /** * @param mediaInfo - * @see https://developers.google.com/cast/docs/reference/chrome/Browser.cast.media.LoadRequest + * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast.media.LoadRequest */ constructor(mediaInfo: Browser.cast.media.MediaInfo); @@ -724,7 +722,7 @@ export namespace Browser { /** * @param opt_activeTrackIds * @param opt_textTrackStyle - * @see https://developers.google.com/cast/docs/reference/chrome/Browser.cast.media.EditTracksInfoRequest + * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast.media.EditTracksInfoRequest */ constructor(activeTrackIds?: number[], textTrackStyle?: Browser.cast.media.TextTrackStyle); @@ -746,7 +744,7 @@ export namespace Browser { export class MovieMediaMetadata { /** - * @see https://developers.google.com/cast/docs/reference/chrome/Browser.cast.media.MovieMediaMetadata + * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast.media.MovieMediaMetadata */ constructor(); @@ -764,7 +762,7 @@ export namespace Browser { export class TvShowMediaMetadata { /** - * @see https://developers.google.com/cast/docs/reference/chrome/Browser.cast.media.TvShowMediaMetadata + * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast.media.TvShowMediaMetadata */ constructor(); @@ -790,7 +788,7 @@ export namespace Browser { export class MusicTrackMediaMetadata { /** - * @see https://developers.google.com/cast/docs/reference/chrome/Browser.cast.media.MusicTrackMediaMetadata + * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast.media.MusicTrackMediaMetadata */ constructor(); @@ -816,7 +814,7 @@ export namespace Browser { export class PhotoMediaMetadata { /** - * @see https://developers.google.com/cast/docs/reference/chrome/Browser.cast.media.PhotoMediaMetadata + * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast.media.PhotoMediaMetadata */ constructor(); @@ -839,7 +837,7 @@ export namespace Browser { /** * @param contentId * @param contentType - * @see https://developers.google.com/cast/docs/reference/chrome/Browser.cast.media.MediaInfo + * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast.media.MediaInfo */ constructor(contentId: string, contentType: string); @@ -857,7 +855,7 @@ export namespace Browser { /** * @param sessionId * @param mediaSessionId - * @see https://developers.google.com/cast/docs/reference/chrome/Browser.cast.media.Media + * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast.media.Media */ constructor(sessionId: string, mediaSessionId: number); @@ -960,7 +958,7 @@ export namespace Browser { /** * @param command - * @return whether or not the receiver supports the given Browser.cast.media.MediaCommand + * @return whether or not the receiver supports the given chrome.cast.media.MediaCommand */ supportsCommand(command: Browser.cast.media.MediaCommand): boolean; @@ -1087,7 +1085,7 @@ export namespace Browser { /** * @param trackId * @param trackType - * @see https://developers.google.com/cast/docs/reference/chrome/Browser.cast.media.Track + * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast.media.Track */ constructor(trackId: number, trackType: Browser.cast.media.TrackType); @@ -1103,7 +1101,7 @@ export namespace Browser { export class TextTrackStyle { /** - * @see https://developers.google.com/cast/docs/reference/chrome/Browser.cast.media.TextTrackStyle + * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast.media.TextTrackStyle */ constructor(); @@ -1127,7 +1125,7 @@ export namespace Browser { * @param end * @param isMovingWindow * @param isLiveDone - * @see https://developers.google.com/cast/docs/reference/chrome/Browser.cast.media.LiveSeekableRange + * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast.media.LiveSeekableRange */ constructor(start?: number, end?: number, isMovingWindow?: boolean, isLiveDone?: boolean); @@ -1139,7 +1137,7 @@ export namespace Browser { } /** - * @see https://developers.google.com/cast/docs/reference/chrome/Browser.cast.media.timeout + * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast.media.timeout */ export namespace cast.media.timeout { export var load: number; @@ -1157,4 +1155,3 @@ export namespace Browser { export var queueUpdate: number; } } - diff --git a/packages/browser/src/gen/har-format/index.d.ts b/packages/browser/src/gen/har-format/index.d.ts index 9827a59f1..33b39ffbc 100644 --- a/packages/browser/src/gen/har-format/index.d.ts +++ b/packages/browser/src/gen/har-format/index.d.ts @@ -1,9 +1,6 @@ -/* DO NOT EDIT - generated by scripts/generate.ts */ - import { Entry, Log } from "har-format"; declare global { export type HARFormatEntry = Entry; export type HARFormatLog = Log; } - diff --git a/packages/browser/src/gen/index.d.ts b/packages/browser/src/gen/index.d.ts index 63a34b6d0..3f42863da 100644 --- a/packages/browser/src/gen/index.d.ts +++ b/packages/browser/src/gen/index.d.ts @@ -1,171 +1,135 @@ /* DO NOT EDIT - generated by scripts/generate.ts */ - -/// /// /// - -// Helpers -type SetRequired = Omit & Required>; - -//////////////////// -// Global object -//////////////////// -interface Window { - // chrome: typeof chrome; -} - +/// export namespace Browser { - //////////////////// - // Accessibility Features - //////////////////// /** - * Use the `Browser.accessibilityFeatures` API to manage Chrome's accessibility features. This API relies on the ChromeSetting prototype of the type API for getting and setting individual accessibility features. In order to get feature states the extension must request `accessibilityFeatures.read` permission. For modifying feature state, the extension needs `accessibilityFeatures.modify` permission. Note that `accessibilityFeatures.modify` does not imply `accessibilityFeatures.read` permission. + * Use the `chrome.accessibilityFeatures` API to manage Chrome's accessibility features. This API relies on the ChromeSetting prototype of the type API for getting and setting individual accessibility features. In order to get feature states the extension must request `accessibilityFeatures.read` permission. For modifying feature state, the extension needs `accessibilityFeatures.modify` permission. Note that `accessibilityFeatures.modify` does not imply `accessibilityFeatures.read` permission. * * Permissions: "accessibilityFeatures.read", "accessibilityFeatures.modify" */ export namespace accessibilityFeatures { /** `get()` requires `accessibilityFeatures.read` permission. `set()` and `clear()` require `accessibilityFeatures.modify` permission. */ - export const animationPolicy: Browser.types.ChromeSetting<"allowed" | "once" | "none">; - + export const animationPolicy: chrome.types.ChromeSetting<"allowed" | "once" | "none">; /** * Auto mouse click after mouse stops moving. The value indicates whether the feature is enabled or not. * `get()` requires `accessibilityFeatures.read` permission. `set()` and `clear()` require `accessibilityFeatures.modify` permission. * @platform ChromeOS only */ - export const autoclick: Browser.types.ChromeSetting; - + export const autoclick: chrome.types.ChromeSetting; /** * Caret highlighting. The value indicates whether the feature is enabled or not. * `get()` requires `accessibilityFeatures.read` permission. `set()` and `clear()` require `accessibilityFeatures.modify` permission. * @platform ChromeOS only * @since Chrome 51 */ - export const caretHighlight: Browser.types.ChromeSetting; - + export const caretHighlight: chrome.types.ChromeSetting; /** * Cursor color. The value indicates whether the feature is enabled or not, doesn't indicate the color of it. * `get()` requires `accessibilityFeatures.read` permission. `set()` and `clear()` require `accessibilityFeatures.modify` permission. * @platform ChromeOS only * @since Chrome 85 */ - export const cursorColor: Browser.types.ChromeSetting; - + export const cursorColor: chrome.types.ChromeSetting; /** * Cursor highlighting. The value indicates whether the feature is enabled or not. * `get()` requires `accessibilityFeatures.read` permission. `set()` and `clear()` require `accessibilityFeatures.modify` permission. * @platform ChromeOS only * @since Chrome 51 */ - export const cursorHighlight: Browser.types.ChromeSetting; - + export const cursorHighlight: chrome.types.ChromeSetting; /** * Dictation. The value indicates whether the feature is enabled or not. * `get()` requires `accessibilityFeatures.read` permission. `set()` and `clear()` require `accessibilityFeatures.modify` permission. * @platform ChromeOS only * @since Chrome 90 */ - export const dictation: Browser.types.ChromeSetting; - + export const dictation: chrome.types.ChromeSetting; /** * Docked magnifier. The value indicates whether docked magnifier feature is enabled or not. * `get()` requires `accessibilityFeatures.read` permission. `set()` and `clear()` require `accessibilityFeatures.modify` permission. * @platform ChromeOS only * @since Chrome 87 */ - export const dockedMagnifier: Browser.types.ChromeSetting; - + export const dockedMagnifier: chrome.types.ChromeSetting; /** * Focus highlighting. The value indicates whether the feature is enabled or not. * `get()` requires `accessibilityFeatures.read` permission. `set()` and `clear()` require `accessibilityFeatures.modify` permission. * @platform ChromeOS only * @since Chrome 51 */ - export const focusHighlight: Browser.types.ChromeSetting; - + export const focusHighlight: chrome.types.ChromeSetting; /** * High contrast rendering mode. The value indicates whether the feature is enabled or not. * `get()` requires `accessibilityFeatures.read` permission. `set()` and `clear()` require `accessibilityFeatures.modify` permission. * @platform ChromeOS only */ - export const highContrast: Browser.types.ChromeSetting; - + export const highContrast: chrome.types.ChromeSetting; /** * Enlarged cursor. The value indicates whether the feature is enabled or not. * `get()` requires `accessibilityFeatures.read` permission. `set()` and `clear()` require `accessibilityFeatures.modify` permission. * @platform ChromeOS only */ - export const largeCursor: Browser.types.ChromeSetting; - + export const largeCursor: chrome.types.ChromeSetting; /** * Full screen magnification. The value indicates whether the feature is enabled or not. * `get()` requires `accessibilityFeatures.read` permission. `set()` and `clear()` require `accessibilityFeatures.modify` permission. * @platform ChromeOS only */ - export const screenMagnifier: Browser.types.ChromeSetting; - + export const screenMagnifier: chrome.types.ChromeSetting; /** * Select-to-speak. The value indicates whether the feature is enabled or not. * `get()` requires `accessibilityFeatures.read` permission. `set()` and `clear()` require `accessibilityFeatures.modify` permission. * @platform ChromeOS only * @since Chrome 51 */ - export const selectToSpeak: Browser.types.ChromeSetting; - + export const selectToSpeak: chrome.types.ChromeSetting; /** * Spoken feedback (text-to-speech). The value indicates whether the feature is enabled or not. * `get()` requires `accessibilityFeatures.read` permission. `set()` and `clear()` require `accessibilityFeatures.modify` permission. * @platform ChromeOS only */ - export const spokenFeedback: Browser.types.ChromeSetting; - + export const spokenFeedback: chrome.types.ChromeSetting; /** * Sticky modifier keys (like shift or alt). The value indicates whether the feature is enabled or not. * `get()` requires `accessibilityFeatures.read` permission. `set()` and `clear()` require `accessibilityFeatures.modify` permission. * @platform ChromeOS only */ - export const stickyKeys: Browser.types.ChromeSetting; - + export const stickyKeys: chrome.types.ChromeSetting; /** * Switch Access. The value indicates whether the feature is enabled or not. * `get()` requires `accessibilityFeatures.read` permission. `set()` and `clear()` require `accessibilityFeatures.modify` permission. * @platform ChromeOS only * @since Chrome 51 */ - export const switchAccess: Browser.types.ChromeSetting; - + export const switchAccess: chrome.types.ChromeSetting; /** * Virtual on-screen keyboard. The value indicates whether the feature is enabled or not. * `get()` requires `accessibilityFeatures.read` permission. `set()` and `clear()` require `accessibilityFeatures.modify` permission. * @platform ChromeOS only */ - export const virtualKeyboard: Browser.types.ChromeSetting; + export const virtualKeyboard: chrome.types.ChromeSetting; } - //////////////////// - // Action - //////////////////// /** - * Use the `Browser.action` API to control the extension's icon in the Google Chrome toolbar. + * Use the `chrome.action` API to control the extension's icon in the Google Chrome toolbar. * The action icons are displayed in the browser toolbar next to the omnibox. After installation, these appear in the extensions menu (the puzzle piece icon). Users can pin your extension icon to the toolbar. * * Manifest: "action" * @since Chrome 88, MV3 */ export namespace action { - /** @deprecated Use BadgeColorDetails instead. */ - export interface BadgeBackgroundColorDetails extends BadgeColorDetails {} - 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. */ + /** 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. */ + /** Limits the change to when a particular tab is selected. Automatically resets when the tab is closed. */ tabId?: number | undefined; } export interface BadgeTextDetails { - /** Any number of characters can be passed, but only about four can fit in the space. */ - text: string; - /** Optional. Limits the change to when a particular tab is selected. Automatically resets when the tab is closed. */ + /** Any number of characters can be passed, but only about four can fit in 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 | undefined; + /** Limits the change to when a particular tab is selected. Automatically resets when the tab is closed. */ tabId?: number | undefined; } @@ -174,33 +138,34 @@ export namespace Browser { export interface TitleDetails { /** The string the 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. */ + /** Limits the change to when a particular tab is selected. Automatically resets when the tab is closed. */ tabId?: number | undefined; } export interface PopupDetails { - /** Optional. Limits the change to when a particular tab is selected. Automatically resets when the tab is closed. */ + /** Limits the change to when a particular tab is selected. Automatically resets when the tab is closed. */ tabId?: number | undefined; - /** The html file to show in a popup. If set to the empty string (''), no popup is shown. */ + /** The html file to show in a popup. If set to the empty string (`''`), no popup is shown. */ popup: string; } 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}' */ + /** 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: number]: string } | undefined; - /** Optional. Limits the change to when a particular tab is selected. Automatically resets when the tab is closed. */ + /** 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}' */ + /** 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; } + /** @since Chrome 99 */ export interface OpenPopupOptions { - /** Optional. The id of the window to open the action popup in. Defaults to the currently-active window if unspecified. */ + /** The id of the window to open the action popup in. Defaults to the currently-active window if unspecified. */ windowId?: number | undefined; } export interface TabDetails { - /** Optional. The ID of the tab to query state for. If no tab is specified, the non-tab-specific state is returned. */ + /** The ID of the tab to query state for. If no tab is specified, the non-tab-specific state is returned. */ tabId?: number | undefined; } @@ -220,292 +185,340 @@ export namespace Browser { } /** - * @since Chrome 88 * Disables the action for a tab. - * @param tabId The id of the tab for which you want to modify the action. - * @return The `disable` method provides its result via callback or returned as a `Promise` (MV3 only). It has no parameters. + * @param tabId The ID of the tab for which you want to modify the action. + * + * Can return its result via Promise. */ export function disable(tabId?: number): Promise; - - /** - * @since Chrome 88 - * Disables the action for a tab. - * @param tabId The id of the tab for which you want to modify the action. - * @param callback - */ export function disable(callback: () => void): void; - export function disable(tabId: number, callback: () => void): void; - + export function disable(tabId: number | undefined, callback: () => void): void; /** - * @since Chrome 88 * Enables the action for a tab. By default, actions are enabled. - * @param tabId The id of the tab for which you want to modify the action. - * @return The `enable` method provides its result via callback or returned as a `Promise` (MV3 only). It has no parameters. + * @param tabId The ID of the tab for which you want to modify the action. + * + * Can return its result via Promise. */ export function enable(tabId?: number): Promise; - - /** - * @since Chrome 88 - * Enables the action for a tab. By default, actions are enabled. - * @param tabId The id of the tab for which you want to modify the action. - * @param callback - */ export function enable(callback: () => void): void; - export function enable(tabId: number, callback: () => void): void; - + export function enable(tabId: number | undefined, callback: () => void): void; /** - * @since Chrome 88 - * Gets the background color of the action. - */ - export function getBadgeBackgroundColor(details: TabDetails, callback: (result: ColorArray) => void): void; - /** - * @since Chrome 88 * Gets the background color of the action. - * @return The `getBadgeBackgroundColor` method provides its result via callback or returned as a `Promise` (MV3 only). + * + * Can return its result via Promise. */ export function getBadgeBackgroundColor(details: TabDetails): Promise; - - /** - * @since Chrome 88 - * Gets the badge text of the action. If no tab is specified, the non-tab-specific badge text is returned. - * If displayActionCountAsBadgeText is enabled, a placeholder text will be returned unless the - * declarativeNetRequestFeedback permission is present or tab-specific badge text was provided. - */ - export function getBadgeText(details: TabDetails, callback: (result: string) => void): void; - + export function getBadgeBackgroundColor(details: TabDetails, callback: (result: ColorArray) => void): void; /** - * @since Chrome 88 - * Gets the badge text of the action. If no tab is specified, the non-tab-specific badge text is returned. - * If displayActionCountAsBadgeText is enabled, a placeholder text will be returned unless the - * declarativeNetRequestFeedback permission is present or tab-specific badge text was provided. - * @return The `getBadgeText` method provides its result via callback or returned as a `Promise` (MV3 only). + * 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. + * + * Can return its result via Promise. */ export function getBadgeText(details: TabDetails): Promise; - + export function getBadgeText(details: TabDetails, callback: (result: string) => void): void; /** - * @since Chrome 110 * Gets the text color of the action. - */ - export function getBadgeTextColor(details: TabDetails, callback: (result: ColorArray) => void): void; - - /** + * + * Can return its result via Promise. * @since Chrome 110 - * Gets the text color of the action. - * @return The `getBadgeTextColor` method provides its result via callback or returned as a `Promise` (MV3 only). */ export function getBadgeTextColor(details: TabDetails): Promise; - - /** - * @since Chrome 88 - * Gets the html document set as the popup for this action. - */ - export function getPopup(details: TabDetails, callback: (result: string) => void): void; - + export function getBadgeTextColor(details: TabDetails, callback: (result: ColorArray) => void): void; /** - * @since Chrome 88 * Gets the html document set as the popup for this action. - * @return The `getPopup` method provides its result via callback or returned as a `Promise` (MV3 only). + * + * Can return its result via Promise. */ export function getPopup(details: TabDetails): Promise; - - /** - * @since Chrome 88 - * Gets the title of the action. - */ - export function getTitle(details: TabDetails, callback: (result: string) => void): void; - + export function getPopup(details: TabDetails, callback: (result: string) => void): void; /** - * @since Chrome 88 * Gets the title of the action. - * @return The `getTitle` method provides its result via callback or returned as a `Promise` (MV3 only). + * + * Can return its result via Promise. */ export function getTitle(details: TabDetails): Promise; - + export function getTitle(details: TabDetails, callback: (result: string) => void): void; /** - * @since Chrome 91 * Returns the user-specified settings relating to an extension's action. - */ - export function getUserSettings(callback: (userSettings: UserSettings) => void): void; - - /** + * + * Can return its result via Promise. * @since Chrome 91 - * Returns the user-specified settings relating to an extension's action. - * @return The `getUserSettings` method provides its result via callback or returned as a `Promise` (MV3 only). */ export function getUserSettings(): Promise; - - /** - * @since Chrome 110 - * Indicates whether the extension action is enabled for a tab (or globally if no tabId is provided). Actions enabled using only declarativeContent always return false. - */ - export function isEnabled(tabId: number | undefined, callback: (isEnabled: boolean) => void): void; - + export function getUserSettings(callback: (userSettings: UserSettings) => void): void; /** + * Indicates whether the extension action is enabled for a tab (or globally if no `tabId` is provided). Actions enabled using only {@link declarativeContent} always return false. + * + * Can return its result via Promise. * @since Chrome 110 - * Indicates whether the extension action is enabled for a tab (or globally if no tabId is provided). Actions enabled using only declarativeContent always return false. - * @return True if the extension action is enabled. */ export function isEnabled(tabId?: number): Promise; - + export function isEnabled(callback: (isEnabled: boolean) => void): void; + export function isEnabled(tabId: number | undefined, callback: (isEnabled: boolean) => void): void; /** - * @since Chrome 99 - * Opens the extension's popup. + * Opens the extension's popup. Between Chrome 118 and Chrome 126, this is only available to policy installed extensions. + * * @param options Specifies options for opening the popup. - * () => {...} - * @return The `openPopup` method provides its result via callback or returned as a `Promise` (MV3 only). It has no parameters. + * + * Can return its result via Promise. + * @since Chrome 127 */ export function openPopup(options?: OpenPopupOptions): Promise; - - /** - * @since Chrome 99 - * Opens the extension's popup. - * @param options Specifies options for opening the popup. - */ export function openPopup(callback: () => void): void; - export function openPopup(options: OpenPopupOptions, callback: () => void): void; - + export function openPopup(options: OpenPopupOptions | undefined, callback: () => void): void; /** - * @since Chrome 88 * 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. + * + * Can return its result via Promise. */ export function setBadgeBackgroundColor(details: BadgeColorDetails): Promise; - - /** - * @since Chrome 88 - * Sets the background color for the badge. - */ export function setBadgeBackgroundColor(details: BadgeColorDetails, callback: () => void): void; - /** - * @since Chrome 88 * Sets the badge text for the 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. + * + * Can return its result via Promise. */ export function setBadgeText(details: BadgeTextDetails): Promise; - - /** - * @since Chrome 88 - * Sets the badge text for the action. The badge is displayed on top of the icon. - */ export function setBadgeText(details: BadgeTextDetails, callback: () => void): void; - /** - * @since Chrome 110 * Sets the text color for the badge. - * @return The `setBadgeTextColor` method provides its result via callback or returned as a `Promise` (MV3 only). It has no parameters. + * + * Can return its result via Promise. + * @since Chrome 110 */ export function setBadgeTextColor(details: BadgeColorDetails): Promise; - - /** - * @since Chrome 100 - * Sets the text color for the badge. - */ export function setBadgeTextColor(details: BadgeColorDetails, callback: () => void): void; - /** - * @since Chrome 88 - * Sets the icon for the 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. - * @return The `setIcon` method provides its result via callback or returned as a `Promise` (MV3 only). Since Chrome 96. + * Sets the icon for the 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. + * + * Can return its result via Promise. */ export function setIcon(details: TabIconDetails): Promise; export function setIcon(details: TabIconDetails, callback: () => void): void; - /** - * @since Chrome 88 * Sets the html document to be opened as a popup when the user clicks on the action's icon. - * @return The `setPopup` method provides its result via callback or returned as a `Promise` (MV3 only). It has no parameters. + * + * Can return its result via Promise. */ export function setPopup(details: PopupDetails): Promise; - - /** - * @since Chrome 88 - * Sets the html document to be opened as a popup when the user clicks on the action's icon. - */ export function setPopup(details: PopupDetails, callback: () => void): void; - /** - * @since Chrome 88 * Sets the title of the 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. + * + * Can return its result via Promise. */ export function setTitle(details: TitleDetails): Promise; - - /** - * @since Chrome 88 - * Sets the title of the action. This shows up in the tooltip. - */ export function setTitle(details: TitleDetails, callback: () => void): void; - /** Fired when an action icon is clicked. This event will not fire if the action has a popup. */ - export const onClicked: Browser.events.Event<(tab: Browser.tabs.Tab) => void>; - + export const onClicked: events.Event<(tab: chrome.tabs.Tab) => void>; /** * Fired when user-specified settings relating to an extension's action change. * @since Chrome 130 */ - export const onUserSettingsChanged: Browser.events.Event<(change: UserSettingsChange) => void>; - } + export const onUserSettingsChanged: events.Event<(change: UserSettingsChange) => void>; - //////////////////// - // Alarms - //////////////////// - /** - * Use the `Browser.alarms` API to schedule code to run periodically or at a specified time in the future. - * - * Permissions: "alarms" - */ - export namespace alarms { - export interface AlarmCreateInfo { - /** Optional. Length of time in minutes after which the 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. */ - periodInMinutes?: number | undefined; - /** Optional. Time at which the alarm should fire, in milliseconds past the epoch (e.g. Date.now() + n). */ - when?: number | undefined; + /** + * Specifies to which tab or window the value should be set, or from which one it should be retrieved. If no tab nor window is specified, the global value is set or retrieved. + */ + interface Details { + /** + * When setting a value, it will be specific to the specified tab, and will automatically reset when the tab navigates. When getting, specifies the tab to get the value from; if there is no tab-specific value, the window one will be inherited. + */ + tabId?: number | undefined; + /** + * When setting a value, it will be specific to the specified window. When getting, specifies the window to get the value from; if there is no window-specific value, the global one will be inherited. + */ + windowId?: number | undefined; } - 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. */ - scheduledTime: number; - /** Name of this alarm. */ - name: string; + /** Information sent when a browser action is clicked. */ + interface OnClickData { + /** An array of keyboard modifiers that were held while the menu item was clicked. */ + modifiers: _OnClickDataModifiers[]; + /** An integer value of button by which menu item was clicked. */ + button?: number | undefined; } - 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. - * 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). + * Specifies to which tab or window the value should be set, or from which one it should be retrieved. If no tab nor window is specified, the global value is set or retrieved. */ - export function create(alarmInfo: AlarmCreateInfo): Promise; + interface _SetTitleDetails { + /** The string the browser action should display when moused over. */ + title: string | null; + /** + * When setting a value, it will be specific to the specified tab, and will automatically reset when the tab navigates. When getting, specifies the tab to get the value from; if there is no tab-specific value, the window one will be inherited. + */ + tabId?: number | undefined; + /** + * When setting a value, it will be specific to the specified window. When getting, specifies the window to get the value from; if there is no window-specific value, the global one will be inherited. + */ + windowId?: number | undefined; + } + + /** The collection of user-specified settings relating to an extension's action. */ + interface _GetUserSettingsReturnUserSettings { + /** + * Whether the extension's action icon is visible on browser windows' top-level toolbar (i.e., whether the extension has been 'pinned' by the user). + */ + isOnToolbar?: boolean | undefined; + } + /** - * 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). + * Specifies to which tab or window the value should be set, or from which one it should be retrieved. If no tab nor window is specified, the global value is set or retrieved. */ - export function create(name: string, alarmInfo: AlarmCreateInfo): Promise; + interface _SetIconDetails { + /** + * 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?: ImageDataType | { + [key: number]: ImageDataType; + } | 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` * 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 | { + [key: number]: string; + } | undefined; + /** + * When setting a value, it will be specific to the specified tab, and will automatically reset when the tab navigates. When getting, specifies the tab to get the value from; if there is no tab-specific value, the window one will be inherited. + */ + tabId?: number | undefined; + /** + * When setting a value, it will be specific to the specified window. When getting, specifies the window to get the value from; if there is no window-specific value, the global one will be inherited. + */ + windowId?: number | undefined; + } + /** - * 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. + * Specifies to which tab or window the value should be set, or from which one it should be retrieved. If no tab nor window is specified, the global value is set or retrieved. */ - export function create(alarmInfo: AlarmCreateInfo, callback: () => void): void; + interface _SetPopupDetails { + /** The html file to show in a popup. If set to the empty string (''), no popup is shown. */ + popup: string | null; + /** + * When setting a value, it will be specific to the specified tab, and will automatically reset when the tab navigates. When getting, specifies the tab to get the value from; if there is no tab-specific value, the window one will be inherited. + */ + tabId?: number | undefined; + /** + * When setting a value, it will be specific to the specified window. When getting, specifies the window to get the value from; if there is no window-specific value, the global one will be inherited. + */ + windowId?: number | undefined; + } + /** - * 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. + * Specifies to which tab or window the value should be set, or from which one it should be retrieved. If no tab nor window is specified, the global value is set or retrieved. + */ + interface _SetBadgeTextDetails { + /** Any number of characters can be passed, but only about four can fit in the space. */ + text: string | null; + /** + * When setting a value, it will be specific to the specified tab, and will automatically reset when the tab navigates. When getting, specifies the tab to get the value from; if there is no tab-specific value, the window one will be inherited. + */ + tabId?: number | undefined; + /** + * When setting a value, it will be specific to the specified window. When getting, specifies the window to get the value from; if there is no window-specific value, the global one will be inherited. + */ + windowId?: number | undefined; + } + + /** + * Specifies to which tab or window the value should be set, or from which one it should be retrieved. If no tab nor window is specified, the global value is set or retrieved. + */ + interface _SetBadgeBackgroundColorDetails { + color: ColorValue; + /** + * When setting a value, it will be specific to the specified tab, and will automatically reset when the tab navigates. When getting, specifies the tab to get the value from; if there is no tab-specific value, the window one will be inherited. + */ + tabId?: number | undefined; + /** + * When setting a value, it will be specific to the specified window. When getting, specifies the window to get the value from; if there is no window-specific value, the global one will be inherited. + */ + windowId?: number | undefined; + } + + /** + * Specifies to which tab or window the value should be set, or from which one it should be retrieved. If no tab nor window is specified, the global value is set or retrieved. + */ + interface _SetBadgeTextColorDetails { + color: ColorValue; + /** + * When setting a value, it will be specific to the specified tab, and will automatically reset when the tab navigates. When getting, specifies the tab to get the value from; if there is no tab-specific value, the window one will be inherited. + */ + tabId?: number | undefined; + /** + * When setting a value, it will be specific to the specified window. When getting, specifies the window to get the value from; if there is no window-specific value, the global one will be inherited. + */ + windowId?: number | undefined; + } + + /** An object with information about the popup to open. */ + interface _OpenPopupOptions { + /** Defaults to the current window. */ + windowId?: number | undefined; + } + + /** + * Fired when a browser action icon is clicked. This event will not fire if the browser action has a popup. + */ + const onClicked: WebExtEvent<(tab: tabs.Tab, info?: OnClickData) => void>; + } + + /** + * Use the `chrome.alarms` API to schedule code to run periodically or at a specified time in the future. + * + * Permissions: "alarms" + */ + export namespace alarms { + export interface AlarmCreateInfo { + /** Optional. Length of time in minutes after which the 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. */ + periodInMinutes?: number | undefined; + /** Optional. 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. */ + scheduledTime: number; + /** Name of this alarm. */ + name: string; + } + + export interface AlarmEvent extends chrome.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. + * 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). + */ + 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(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; @@ -569,16 +582,30 @@ export namespace Browser { * @return The `get` method provides its result via callback or returned as a `Promise` (MV3 only). */ export function get(name: string): Promise; - /** Fired when an alarm has elapsed. Useful for event pages. */ export var onAlarm: AlarmEvent; + + /** + * Details about the alarm. The alarm first fires either at 'when' milliseconds past the epoch (if 'when' is provided), after 'delayInMinutes' minutes from the current time (if 'delayInMinutes' is provided instead), or after 'periodInMinutes' minutes from the current time (if only 'periodInMinutes' is provided). Users should never provide both 'when' and 'delayInMinutes'. If 'periodInMinutes' is provided, then the alarm recurs repeatedly after that many minutes. + */ + interface _CreateAlarmInfo { + /** Time when the alarm is scheduled to first fire, in milliseconds past the epoch. */ + when?: number | undefined; + /** Number of minutes from the current time after which the alarm should first fire. */ + delayInMinutes?: number | undefined; + /** Number of minutes after which the alarm should recur repeatedly. */ + periodInMinutes?: number | undefined; + } + + /** + * Fired when an alarm has expired. Useful for transient background pages. + * @param name The alarm that has expired. + */ + const onAlarm: WebExtEvent<(name: Alarm) => void>; } - //////////////////// - // Audio - //////////////////// /** - * The `Browser.audio` API is provided to allow users to get information about and control the audio devices attached to the system. This API is currently only available in kiosk mode for ChromeOS. + * The `chrome.audio` API is provided to allow users to get information about and control the audio devices attached to the system. This API is currently only available in kiosk mode for ChromeOS. * * Permissions: "audio" * @platform ChromeOS only @@ -650,7 +677,7 @@ export namespace Browser { POST_DSP_LOOPBACK = "POST_DSP_LOOPBACK", POST_MIX_LOOPBACK = "POST_MIX_LOOPBACK", REAR_MIC = "REAR_MIC", - USB = "USB", + USB = "USB" } export interface LevelChangedEvent { @@ -670,7 +697,7 @@ export namespace Browser { /** Type of stream an audio device provides. */ export enum StreamType { INPUT = "INPUT", - OUTPUT = "OUTPUT", + OUTPUT = "OUTPUT" } /** @@ -680,57 +707,47 @@ export namespace Browser { export function getDevices(filter?: DeviceFilter): Promise; export function getDevices(filter: DeviceFilter, callback: (devices: AudioDeviceInfo[]) => void): void; export function getDevices(callback: (devices: AudioDeviceInfo[]) => void): void; - /** * Gets the system-wide mute state for the specified stream type. * Can return its result via Promise in Manifest V3 or later since Chrome 116. */ export function getMute(streamType: `${StreamType}`): Promise; export function getMute(streamType: `${StreamType}`, callback: (value: boolean) => void): void; - /** * Sets lists of active input and/or output devices. * Can return its result via Promise in Manifest V3 or later since Chrome 116. */ export function setActiveDevices(ids: DeviceIdLists): Promise; export function setActiveDevices(ids: DeviceIdLists, callback: () => void): void; - /** * Sets mute state for a stream type. The mute state will apply to all audio devices with the specified audio stream type. * Can return its result via Promise in Manifest V3 or later since Chrome 116. */ export function setMute(streamType: `${StreamType}`, isMuted: boolean): Promise; export function setMute(streamType: `${StreamType}`, isMuted: boolean, callback: () => void): void; - /** * Sets the properties for the input or output device. * Can return its result via Promise in Manifest V3 or later since Chrome 116. */ export function setProperties(id: string, properties: DeviceProperties): Promise; export function setProperties(id: string, properties: DeviceProperties, callback: () => void): void; - /** * Fired when audio devices change, either new devices being added, or existing devices being removed. */ - export const onDeviceListChanged: Browser.events.Event<(devices: AudioDeviceInfo[]) => void>; - + export const onDeviceListChanged: chrome.events.Event<(devices: AudioDeviceInfo[]) => void>; /** * Fired when sound level changes for an active audio device. */ - export const onLevelChanged: Browser.events.Event<(event: LevelChangedEvent) => void>; - + export const onLevelChanged: chrome.events.Event<(event: LevelChangedEvent) => void>; /** * Fired when the mute state of the audio input or output changes. * Note that mute state is system-wide and the new value applies to every audio device with specified stream type. */ - export const onMuteChanged: Browser.events.Event<(event: MuteChangedEvent) => void>; + export const onMuteChanged: chrome.events.Event<(event: MuteChangedEvent) => void>; } - //////////////////// - // Browser - //////////////////// /** - * Use the Browser.browser API to interact with the Chrome browser associated with + * Use the chrome.browser API to interact with the Chrome browser associated with * the current application and Chrome profile. * @deprecated Part of the deprecated Chrome Apps platform */ @@ -749,7 +766,6 @@ export namespace Browser { * created, or failed to be created. If failed, runtime.lastError will be set. */ export function openTab(options: Options, callback: () => void): void; - /** * Opens a new tab in a browser window associated with the current application * and Chrome profile. If no browser window for the Chrome profile is opened, @@ -760,11 +776,8 @@ export namespace Browser { export function openTab(options: Options): void; } - //////////////////// - // Bookmarks - //////////////////// /** - * Use the `Browser.bookmarks` API to create, organize, and otherwise manipulate bookmarks. Also see Override Pages, which you can use to create a custom Bookmark Manager page. + * Use the `chrome.bookmarks` API to create, organize, and otherwise manipulate bookmarks. Also see Override Pages, which you can use to create a custom Bookmark Manager page. * * Permissions: "bookmarks" */ @@ -808,7 +821,6 @@ export namespace Browser { title: string; /** Indicates the reason why this node is unmodifiable. The `managed` value indicates that this node was configured by the system administrator or by the custodian of a supervised user. Omitted if the node can be modified by the user and the extension (default). */ unmodifiable?: `${BookmarkTreeNodeUnmodifiable}`; - /* The URL navigated to when a user clicks the bookmark. Omitted for folders. */ url?: string; } @@ -817,7 +829,7 @@ export namespace Browser { * @since Chrome 44 */ export enum BookmarkTreeNodeUnmodifiable { - MANAGED = "managed", + MANAGED = "managed" } /** Object passed to the create() function. */ @@ -833,7 +845,6 @@ export namespace Browser { * Indicates the type of folder. * @since Chrome 134 */ - export enum FolderType { /** The folder whose contents is displayed at the top of the browser window. */ BOOKMARKS_BAR = "bookmarks-bar", @@ -842,14 +853,13 @@ export namespace Browser { /** Bookmarks generally available on the user's mobile devices, but modifiable by extension or in the bookmarks manager. */ MOBILE = "mobile", /** A top-level folder that may be present if the system administrator or the custodian of a supervised user has configured bookmarks. */ - MANAGED = "managed", + MANAGED = "managed" } /** @deprecated Bookmark write operations are no longer limited by Chrome. */ export const MAX_WRITE_OPERATIONS_PER_HOUR: 1000000; /** @deprecated Bookmark write operations are no longer limited by Chrome. */ export const MAX_SUSTAINED_WRITE_OPERATIONS_PER_MINUTE: 1000000; - /** * Creates a bookmark or folder under the specified parentId. If url is NULL or missing, it will be a folder. * @@ -857,7 +867,6 @@ export namespace Browser { */ export function create(bookmark: CreateDetails): Promise; export function create(bookmark: CreateDetails, callback: (result: BookmarkTreeNode) => void): void; - /** * Retrieves the specified BookmarkTreeNode(s). * @param idOrIdList A single string-valued id, or an array of string-valued ids @@ -865,11 +874,7 @@ export namespace Browser { * Can return its result via Promise since Chrome 90. */ export function get(idOrIdList: string | [string, ...string[]]): Promise; - export function get( - idOrIdList: string | [string, ...string[]], - callback: (results: BookmarkTreeNode[]) => void, - ): void; - + export function get(idOrIdList: string | [string, ...string[]], callback: (results: BookmarkTreeNode[]) => void): void; /** * Retrieves the children of the specified BookmarkTreeNode id. * @@ -877,7 +882,6 @@ export namespace Browser { */ export function getChildren(id: string): Promise; export function getChildren(id: string, callback: (results: BookmarkTreeNode[]) => void): void; - /** * Retrieves the recently added bookmarks. * @param numberOfItems The maximum number of items to return. @@ -886,7 +890,6 @@ export namespace Browser { */ export function getRecent(numberOfItems: number): Promise; export function getRecent(numberOfItems: number, callback: (results: BookmarkTreeNode[]) => void): void; - /** * Retrieves part of the Bookmarks hierarchy, starting at the specified node. * @param id The ID of the root of the subtree to retrieve. @@ -895,7 +898,6 @@ export namespace Browser { */ export function getSubTree(id: string): Promise; export function getSubTree(id: string, callback: (results: BookmarkTreeNode[]) => void): void; - /** * Retrieves the entire Bookmarks hierarchy. * @@ -915,12 +917,7 @@ export namespace Browser { * Can return its result via Promise since Chrome Chrome 90 */ export function move(id: string, destination: MoveDestination): Promise; - export function move( - id: string, - destination: MoveDestination, - callback: (result: BookmarkTreeNode) => void, - ): void; - + export function move(id: string, destination: MoveDestination, callback: (result: BookmarkTreeNode) => void): void; /** * Removes a bookmark or an empty bookmark folder. * @@ -928,7 +925,6 @@ export namespace Browser { */ export function remove(id: string): Promise; export function remove(id: string, callback: () => void): void; - /** * Recursively removes a bookmark folder. * @@ -938,7 +934,7 @@ export namespace Browser { export function removeTree(id: string, callback: () => void): void; interface SearchQuery { - /** A string of words and quoted phrases that are matched against bookmark URLs and titles.*/ + /** A string of words and quoted phrases that are matched against bookmark URLs and titles. */ query?: string; /** The URL of the bookmark; matches verbatim. Note that folders have no URL. */ url?: string; @@ -967,52 +963,93 @@ export namespace Browser { */ export function update(id: string, changes: UpdateChanges): Promise; export function update(id: string, changes: UpdateChanges, callback: (result: BookmarkTreeNode) => void): void; - - /** Fired when a bookmark or folder changes. **Note:** Currently, only title and url changes trigger this.*/ + /** Fired when a bookmark or folder changes. **Note:** Currently, only title and url changes trigger this. */ export const onChanged: events.Event<(id: string, changeInfo: { title: string; url?: string }) => void>; - /** Fired when the children of a folder have changed their order due to the order being sorted in the UI. This is not called as a result of a move(). */ export const onChildrenReordered: events.Event<(id: string, reorderInfo: { childIds: string[] }) => void>; - /** Fired when a bookmark or folder is created. */ export const onCreated: events.Event<(id: string, bookmark: BookmarkTreeNode) => void>; - /** Fired when a bookmark import session is begun. Expensive observers should ignore onCreated updates until onImportEnded is fired. Observers should still handle other notifications immediately. */ export const onImportBegan: events.Event<() => void>; - - /** Fired when a bookmark import session is ended. */ + /** Fired when a bookmark import session is ended. */ export const onImportEnded: events.Event<() => void>; - /** Fired when a bookmark or folder is moved to a different parent folder. */ export const onMoved: events.Event< - ( - id: string, - moveInfo: { - parentId: string; - index: number; - oldParentId: string; - oldIndex: number; - }, - ) => void - >; - + ( + id: string, + moveInfo: { + parentId: string; + index: number; + oldParentId: string; + oldIndex: number; + }, + ) => void + >; /** Fired when a bookmark or folder is removed. When a folder is removed recursively, a single notification is fired for the folder, and none for its contents. */ export const onRemoved: events.Event< - ( - id: string, - removeInfo: { - parentId: string; - index: number; - /** @since Chrome 48 */ - node: BookmarkTreeNode; - }, - ) => void - >; + ( + id: string, + removeInfo: { + parentId: string; + index: number; + /** @since Chrome 48 */ + node: BookmarkTreeNode; + }, + ) => void + >; + + interface _MoveDestination { + parentId?: string | undefined; + index?: number | undefined; + } + + interface _UpdateChanges { + title?: string | undefined; + url?: string | undefined; + } + + interface _OnRemovedRemoveInfo { + parentId: string; + index: number; + node: BookmarkTreeNode; + } + + interface _OnChangedChangeInfo { + title: string; + url?: string | undefined; + } + + interface _OnMovedMoveInfo { + parentId: string; + index: number; + oldParentId: string; + oldIndex: number; + } + + interface _OnChildrenReorderedReorderInfo { + childIds: string[]; + } + + /** Fired when a bookmark or folder is created. */ + const onCreated: WebExtEvent<(id: string, bookmark: BookmarkTreeNode) => void>; + /** + * Fired when a bookmark or folder is removed. When a folder is removed recursively, a single notification is fired for the folder, and none for its contents. + */ + const onRemoved: WebExtEvent<(id: string, removeInfo: _OnRemovedRemoveInfo) => void>; + /** + * Fired when a bookmark or folder changes. **Note:** Currently, only title and url changes trigger this. + */ + const onChanged: WebExtEvent<(id: string, changeInfo: _OnChangedChangeInfo) => void>; + /** Fired when a bookmark or folder is moved to a different parent folder. */ + const onMoved: WebExtEvent<(id: string, moveInfo: _OnMovedMoveInfo) => void>; + /** + * Fired when the children of a folder have changed their order due to the order being sorted in the UI. This is not called as a result of a move(). + * @deprecated Unsupported on Firefox at this time. + */ + const onChildrenReordered: | WebExtEvent<(id: string, reorderInfo: _OnChildrenReorderedReorderInfo) => void> + | undefined; } - //////////////////// - // Browser Action - //////////////////// /** * Use browser actions to put icons in the main Google Chrome toolbar, to the right of the address bar. In addition to its icon, a browser action can have a tooltip, a badge, and a popup. * @@ -1024,14 +1061,14 @@ export namespace Browser { 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. */ + /** Optional. Limits the change to when a particular tab is selected. Automatically resets when the tab is closed. */ tabId?: number | undefined; } export interface BadgeTextDetails { /** Any number of characters can be passed, but only about four can fit in the space. */ text?: string | null | undefined; - /** Optional. Limits the change to when a particular tab is selected. Automatically resets when the tab is closed. */ + /** Optional. Limits the change to when a particular tab is selected. Automatically resets when the tab is closed. */ tabId?: number | undefined; } @@ -1040,32 +1077,33 @@ export namespace Browser { 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. */ + /** Optional. Limits the change to when a particular tab is selected. Automatically resets when the tab is closed. */ tabId?: number | null; } export interface TabDetails { - /** Optional. Specify the tab to get the information. If no tab is specified, the non-tab-specific information is returned. */ + /** Optional. Specify the tab to get the information. If no tab is specified, the non-tab-specific information is returned. */ tabId?: number | null; } 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}' */ + /** 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. */ + /** 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}' */ + /** 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 interface PopupDetails { - /** Optional. Limits the change to when a particular tab is selected. Automatically resets when the tab is closed. */ + /** 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. */ popup: string; } - export interface BrowserClickedEvent extends Browser.events.Event<(tab: Browser.tabs.Tab) => void> {} + export interface BrowserClickedEvent extends chrome.events.Event<(tab: chrome.tabs.Tab) => void> { + } /** * @since Chrome 22 @@ -1186,26 +1224,176 @@ export namespace Browser { * 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. */ 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; + + /** + * Specifies to which tab or window the value should be set, or from which one it should be retrieved. If no tab nor window is specified, the global value is set or retrieved. + */ + interface Details { + /** + * When setting a value, it will be specific to the specified tab, and will automatically reset when the tab navigates. When getting, specifies the tab to get the value from; if there is no tab-specific value, the window one will be inherited. + */ + tabId?: number | undefined; + /** + * When setting a value, it will be specific to the specified window. When getting, specifies the window to get the value from; if there is no window-specific value, the global one will be inherited. + */ + windowId?: number | undefined; + } + + /** Information sent when a browser action is clicked. */ + interface OnClickData { + /** An array of keyboard modifiers that were held while the menu item was clicked. */ + modifiers: _OnClickDataModifiers[]; + /** An integer value of button by which menu item was clicked. */ + button?: number | undefined; + } + + /** + * Specifies to which tab or window the value should be set, or from which one it should be retrieved. If no tab nor window is specified, the global value is set or retrieved. + */ + interface _SetTitleDetails { + /** The string the browser action should display when moused over. */ + title: string | null; + /** + * When setting a value, it will be specific to the specified tab, and will automatically reset when the tab navigates. When getting, specifies the tab to get the value from; if there is no tab-specific value, the window one will be inherited. + */ + tabId?: number | undefined; + /** + * When setting a value, it will be specific to the specified window. When getting, specifies the window to get the value from; if there is no window-specific value, the global one will be inherited. + */ + windowId?: number | undefined; + } + + /** + * Specifies to which tab or window the value should be set, or from which one it should be retrieved. If no tab nor window is specified, the global value is set or retrieved. + */ + interface _SetIconDetails { + /** + * 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?: ImageDataType | { + [key: number]: ImageDataType; + } | 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` * 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 | { + [key: number]: string; + } | undefined; + /** + * When setting a value, it will be specific to the specified tab, and will automatically reset when the tab navigates. When getting, specifies the tab to get the value from; if there is no tab-specific value, the window one will be inherited. + */ + tabId?: number | undefined; + /** + * When setting a value, it will be specific to the specified window. When getting, specifies the window to get the value from; if there is no window-specific value, the global one will be inherited. + */ + windowId?: number | undefined; + } + + /** + * Specifies to which tab or window the value should be set, or from which one it should be retrieved. If no tab nor window is specified, the global value is set or retrieved. + */ + interface _SetPopupDetails { + /** The html file to show in a popup. If set to the empty string (''), no popup is shown. */ + popup: string | null; + /** + * When setting a value, it will be specific to the specified tab, and will automatically reset when the tab navigates. When getting, specifies the tab to get the value from; if there is no tab-specific value, the window one will be inherited. + */ + tabId?: number | undefined; + /** + * When setting a value, it will be specific to the specified window. When getting, specifies the window to get the value from; if there is no window-specific value, the global one will be inherited. + */ + windowId?: number | undefined; + } + + /** + * Specifies to which tab or window the value should be set, or from which one it should be retrieved. If no tab nor window is specified, the global value is set or retrieved. + */ + interface _SetBadgeTextDetails { + /** Any number of characters can be passed, but only about four can fit in the space. */ + text: string | null; + /** + * When setting a value, it will be specific to the specified tab, and will automatically reset when the tab navigates. When getting, specifies the tab to get the value from; if there is no tab-specific value, the window one will be inherited. + */ + tabId?: number | undefined; + /** + * When setting a value, it will be specific to the specified window. When getting, specifies the window to get the value from; if there is no window-specific value, the global one will be inherited. + */ + windowId?: number | undefined; + } + + /** + * Specifies to which tab or window the value should be set, or from which one it should be retrieved. If no tab nor window is specified, the global value is set or retrieved. + */ + interface _SetBadgeBackgroundColorDetails { + color: ColorValue; + /** + * When setting a value, it will be specific to the specified tab, and will automatically reset when the tab navigates. When getting, specifies the tab to get the value from; if there is no tab-specific value, the window one will be inherited. + */ + tabId?: number | undefined; + /** + * When setting a value, it will be specific to the specified window. When getting, specifies the window to get the value from; if there is no window-specific value, the global one will be inherited. + */ + windowId?: number | undefined; + } + + /** + * Specifies to which tab or window the value should be set, or from which one it should be retrieved. If no tab nor window is specified, the global value is set or retrieved. + */ + interface _SetBadgeTextColorDetails { + color: ColorValue; + /** + * When setting a value, it will be specific to the specified tab, and will automatically reset when the tab navigates. When getting, specifies the tab to get the value from; if there is no tab-specific value, the window one will be inherited. + */ + tabId?: number | undefined; + /** + * When setting a value, it will be specific to the specified window. When getting, specifies the window to get the value from; if there is no window-specific value, the global one will be inherited. + */ + windowId?: number | undefined; + } + + /** An object with information about the popup to open. */ + interface _OpenPopupOptions { + /** Defaults to the current window. */ + windowId?: number | undefined; + } + + /** Returns the user-specified settings relating to an extension's action. */ + function getUserSettings(): Promise; + /** + * Sets the text color for the badge. + * @param details Specifies to which tab or window the value should be set, or from which one it should be retrieved. If no tab nor window is specified, the global value is set or retrieved. + */ + function setBadgeTextColor(details: _SetBadgeTextColorDetails): Promise; + /** Gets the text color of the browser action badge. */ + function getBadgeTextColor(details: Details): Promise; + /** Checks whether the browser action is enabled. */ + function isEnabled(details: Details): Promise; + /** + * Opens the extension popup window in the specified window. + * @param [options] An object with information about the popup to open. + */ + function openPopup(options?: _OpenPopupOptions): Promise; + + /** + * Fired when a browser action icon is clicked. This event will not fire if the browser action has a popup. + */ + const onClicked: WebExtEvent<(tab: tabs.Tab, info?: OnClickData) => void>; } - //////////////////// - // Browsing Data - //////////////////// /** - * Use the `Browser.browsingData` API to remove browsing data from a user's local profile. + * Use the `chrome.browsingData` API to remove browsing data from a user's local profile. * * Permissions: "browsingData" */ export namespace browsingData { export interface OriginTypes { - /** Optional. Extensions and packaged applications a user has installed (be _really_ careful!). */ + /** Optional. Extensions and packaged applications a user has installed (be _really_ careful!). */ extension?: boolean | undefined; - /** Optional. Websites that have been installed as hosted applications (be careful!). */ + /** Optional. Websites that have been installed as hosted applications (be careful!). */ protectedWeb?: boolean | undefined; - /** Optional. Normal websites. */ + /** Optional. Normal websites. */ unprotectedWeb?: boolean | undefined; } @@ -1240,13 +1428,13 @@ export namespace Browser { * A set of data types. Missing data types are interpreted as false. */ export interface DataTypeSet { - /** Optional. Websites' WebSQL data. */ + /** Optional. Websites' WebSQL data. */ webSQL?: boolean | undefined; - /** Optional. Websites' IndexedDB data. */ + /** Optional. Websites' IndexedDB data. */ indexedDB?: boolean | undefined; - /** Optional. The browser's cookies. */ + /** Optional. The browser's cookies. */ cookies?: boolean | undefined; - /** Optional. Stored passwords. */ + /** Optional. Stored passwords. */ passwords?: boolean | undefined; /** * @deprecated Deprecated since Chrome 76. @@ -1255,15 +1443,15 @@ export namespace Browser { * Optional. Server-bound certificates. */ serverBoundCertificates?: boolean | undefined; - /** Optional. The browser's download list. */ + /** Optional. The browser's download list. */ downloads?: boolean | undefined; - /** Optional. The browser's cache. Note: when removing data, this clears the entire cache: it is not limited to the range you specify. */ + /** Optional. The browser's cache. Note: when removing data, this clears the entire cache: it is not limited to the range you specify. */ cache?: boolean | undefined; - /** Optional. The browser's cacheStorage. */ + /** Optional. The browser's cacheStorage. */ cacheStorage?: boolean | undefined; - /** Optional. Websites' appcaches. */ + /** Optional. Websites' appcaches. */ appcache?: boolean | undefined; - /** Optional. Websites' file systems. */ + /** Optional. Websites' file systems. */ fileSystems?: boolean | undefined; /** * @deprecated Deprecated since Chrome 88. @@ -1272,11 +1460,11 @@ export namespace Browser { * Optional. Plugins' data. */ pluginData?: boolean | undefined; - /** Optional. Websites' local storage data. */ + /** Optional. Websites' local storage data. */ localStorage?: boolean | undefined; - /** Optional. The browser's stored form data. */ + /** Optional. The browser's stored form data. */ formData?: boolean | undefined; - /** Optional. The browser's history. */ + /** Optional. The browser's history. */ history?: boolean | undefined; /** * Optional. @@ -1405,11 +1593,13 @@ export namespace Browser { * @param callback Called when websites' appcache data has been cleared. */ export function removeAppcache(options: RemovalOptions, callback: () => void): void; - /** Clears websites' cache storage data. + /** + * Clears websites' cache storage data. * @return The `removeCacheStorage` method provides its result via callback or returned as a `Promise` (MV3 only). It has no parameters. */ export function removeCacheStorage(options: RemovalOptions): Promise; - /** Clears websites' cache storage data. + /** + * Clears websites' cache storage data. * @param callback Called when websites' appcache data has been cleared. */ export function removeCacheStorage(options: RemovalOptions, callback: () => void): void; @@ -1463,27 +1653,278 @@ export namespace Browser { * @param callback Called when websites' IndexedDB data has been cleared. */ export function removeIndexedDB(options: RemovalOptions, callback: () => void): void; - } - //////////////////// - // Commands - //////////////////// - /** - * Use the commands API to add keyboard shortcuts that trigger actions in your extension, for example, an action to open the browser action or send a command to the extension. - * - * Manifest: "commands" - */ - export namespace commands { + /** + * An object whose properties specify which origin types ought to be cleared. If this object isn't specified, it defaults to clearing only "unprotected" origins. Please ensure that you _really_ want to remove application data before adding 'protectedWeb' or 'extensions'. + */ + interface _RemovalOptionsOriginTypes { + /** Normal websites. */ + unprotectedWeb?: boolean | undefined; + /** Websites that have been installed as hosted applications (be careful!). */ + protectedWeb?: boolean | undefined; + /** Extensions and packaged applications a user has installed (be _really_ careful!). */ + extension?: boolean | undefined; + } + + interface _SettingsReturnResult { + options: RemovalOptions; + /** + * All of the types will be present in the result, with values of `true` if they are both selected to be removed and permitted to be removed, otherwise `false`. + */ + dataToRemove: DataTypeSet; + /** + * All of the types will be present in the result, with values of `true` if they are permitted to be removed (e.g., by enterprise policy) and `false` if not. + */ + dataRemovalPermitted: DataTypeSet; + } + } + + /** + * Use this API to expose certificates to the platform which can use these certificates for TLS authentications. + * + * Manifest: "certificateProvider" + * @platform ChromeOS only + * @since Chrome 46 + */ + export namespace certificateProvider { + /** Types of supported cryptographic signature algorithms. */ + export enum Algorithm { + /** + * Specifies the RSASSA PKCS#1 v1.5 signature algorithm with the MD5-SHA-1 hashing. The extension must not prepend a DigestInfo prefix but only add PKCS#1 padding. + * @deprecated This algorithm is deprecated and will never be requested by Chrome as of version 109. + */ + RSASSA_PKCS1_V1_5_MD5_SHA1 = "RSASSA_PKCS1_v1_5_MD5_SHA1", + /** Specifies the RSASSA PKCS#1 v1.5 signature algorithm with the SHA-1 hash function. */ + RSASSA_PKCS1_V1_5_SHA1 = "RSASSA_PKCS1_v1_5_SHA1", + /** Specifies the RSASSA PKCS#1 v1.5 signature algorithm with the SHA-256 hashing function. */ + RSASSA_PKCS1_V1_5_SHA256 = "RSASSA_PKCS1_v1_5_SHA256", + /** Specifies the RSASSA PKCS#1 v1.5 signature algorithm with the SHA-384 hashing function. */ + RSASSA_PKCS1_V1_5_SHA384 = "RSASSA_PKCS1_v1_5_SHA384", + /** Specifies the RSASSA PKCS#1 v1.5 signature algorithm with the SHA-512 hashing function. */ + RSASSA_PKCS1_V1_5_SHA512 = "RSASSA_PKCS1_v1_5_SHA512", + /** Specifies the RSASSA PSS signature algorithm with the SHA-256 hashing function, MGF1 mask generation function and the salt of the same size as the hash. */ + RSASSA_PSS_SHA256 = "RSASSA_PSS_SHA256", + /** Specifies the RSASSA PSS signature algorithm with the SHA-384 hashing function, MGF1 mask generation function and the salt of the same size as the hash. */ + RSASSA_PSS_SHA384 = "RSASSA_PSS_SHA384", + /** Specifies the RSASSA PSS signature algorithm with the SHA-512 hashing function, MGF1 mask generation function and the salt of the same size as the hash. */ + RSASSA_PSS_SHA512 = "RSASSA_PSS_SHA512" + } + + export interface CertificateInfo { + /** Must be the DER encoding of a X.509 certificate. Currently, only certificates of RSA keys are supported. */ + certificate: ArrayBuffer; + /** Must be set to all hashes supported for this certificate. This extension will only be asked for signatures of digests calculated with one of these hash algorithms. This should be in order of decreasing hash preference. */ + supportedHashes: `${Hash}`[]; + } + + /** @since Chrome 86 */ + export interface CertificatesUpdateRequest { + /** Request identifier to be passed to {@link setCertificates}. */ + certificatesRequestId: number; + } + + /** @since Chrome 86 */ + export interface ClientCertificateInfo { + /** + * The array must contain the DER encoding of the X.509 client certificate as its first element. + * + * This must include exactly one certificate. + */ + certificateChain: ArrayBuffer[]; + /** All algorithms supported for this certificate. The extension will only be asked for signatures using one of these algorithms. */ + supportedAlgorithms: `${Algorithm}`[]; + } + + /** + * Types of errors that the extension can report. + * @since Chrome 86 + */ + export enum Error { + GENERAL_ERROR = "GENERAL_ERROR" + } + + /** @deprecated Replaced by {@link Algorithm}. */ + export enum Hash { + /** Specifies the MD5 and SHA1 hashing algorithms. */ + MD5_SHA1 = "MD5_SHA1", + /** Specifies the SHA1 hashing algorithm. */ + SHA1 = "SHA1", + /** Specifies the SHA256 hashing algorithm. */ + SHA256 = "SHA256", + /** Specifies the SHA384 hashing algorithm. */ + SHA384 = "SHA384", + /** Specifies the SHA512 hashing algorithm. */ + SHA512 = "SHA512" + } + + /** + * The types of errors that can be presented to the user through the requestPin function. + * @since Chrome 57 + */ + export enum PinRequestErrorType { + /** Specifies the PIN is invalid. */ + INVALID_PIN = "INVALID_PIN", + /** Specifies the PUK is invalid. */ + INVALID_PUK = "INVALID_PUK", + /** Specifies the maximum attempt number has been exceeded. */ + MAX_ATTEMPTS_EXCEEDED = "MAX_ATTEMPTS_EXCEEDED", + /** Specifies that the error cannot be represented by the above types. */ + UNKNOWN_ERROR = "UNKNOWN_ERROR" + } + + /** + * The type of code being requested by the extension with requestPin function. + * @since Chrome 57 + */ + export enum PinRequestType { + /** Specifies the requested code is a PIN. */ + PIN = "PIN", + /** Specifies the requested code is a PUK. */ + PUK = "PUK" + } + + /** @since Chrome 57 */ + export interface PinResponseDetails { + /** The code provided by the user. Empty if user closed the dialog or some other error occurred. */ + userInput?: string | undefined; + } + + /** @since Chrome 86 */ + export interface ReportSignatureDetails { + /** Error that occurred while generating the signature, if any. */ + error?: `${Error}` | undefined; + /** Request identifier that was received via the {@link onSignatureRequested} event. */ + signRequestId: number; + /** The signature, if successfully generated. */ + signature?: ArrayBuffer | undefined; + } + + /** @since Chrome 57 */ + export interface RequestPinDetails { + /** The number of attempts left. This is provided so that any UI can present this information to the user. Chrome is not expected to enforce this, instead stopPinRequest should be called by the extension with errorType = MAX_ATTEMPTS_EXCEEDED when the number of pin requests is exceeded. */ + attemptsLeft?: number | undefined; + /** The error template displayed to the user. This should be set if the previous request failed, to notify the user of the failure reason. */ + errorType?: `${PinRequestErrorType}` | undefined; + /** The type of code requested. Default is PIN. */ + requestType?: `${PinRequestType}` | undefined; + /** The ID given by Chrome in SignRequest. */ + signRequestId: number; + } + + /** @since Chrome 86 */ + export interface SetCertificatesDetails { + /** When called in response to {@link onCertificatesUpdateRequested}, should contain the received `certificatesRequestId` value. Otherwise, should be unset. */ + certificatesRequestId?: number | undefined; + /** List of currently available client certificates. */ + clientCertificates: ClientCertificateInfo[]; + /** Error that occurred while extracting the certificates, if any. This error will be surfaced to the user when appropriate. */ + error?: `${Error}` | undefined; + } + + /** @since Chrome 86 */ + export interface SignatureRequest { + /** Signature algorithm to be used. */ + algorithm: `${Algorithm}`; + /** The DER encoding of a X.509 certificate. The extension must sign `input` using the associated private key. */ + certificate: ArrayBuffer; + /** Data to be signed. Note that the data is not hashed. */ + input: ArrayBuffer; + /** Request identifier to be passed to {@link reportSignature}. */ + signRequestId: number; + } + + export interface SignRequest { + /** The DER encoding of a X.509 certificate. The extension must sign `digest` using the associated private key. */ + certificate: ArrayBuffer; + /** The digest that must be signed. */ + digest: ArrayBuffer; + /** Refers to the hash algorithm that was used to create `digest`. */ + hash: `${Hash}`; + /** + * The unique ID to be used by the extension should it need to call a method that requires it, e.g. requestPin. + * @since Chrome 57 + */ + signRequestId: number; + } + + /** @since Chrome 57 */ + export interface StopPinRequestDetails { + /** The error template. If present it is displayed to user. Intended to contain the reason for stopping the flow if it was caused by an error, e.g. MAX\_ATTEMPTS\_EXCEEDED. */ + errorType?: `${PinRequestErrorType}` | undefined; + /** The ID given by Chrome in SignRequest. */ + signRequestId: number; + } + + /** + * Should be called as a response to {@link onSignatureRequested}. + * + * The extension must eventually call this function for every {@link onSignatureRequested} event; the API implementation will stop waiting for this call after some time and respond with a timeout error when this function is called. + * + * Can return its result via Promise since Chrome 96. + * @since Chrome 86 + */ + export function reportSignature(details: ReportSignatureDetails): Promise; + export function reportSignature(details: ReportSignatureDetails, callback: () => void): void; + /** + * Requests the PIN from the user. Only one ongoing request at a time is allowed. The requests issued while another flow is ongoing are rejected. It's the extension's responsibility to try again later if another flow is in progress. + * + * Can return its result via Promise since Chrome 96. + * @param details Contains the details about the requested dialog. + * @since Chrome 57 + */ + export function requestPin(details: RequestPinDetails): Promise; + export function requestPin(details: RequestPinDetails, callback: (details?: PinResponseDetails | undefined) => void): void; + /** + * Sets a list of certificates to use in the browser. + * + * The extension should call this function after initialization and on every change in the set of currently available certificates. The extension should also call this function in response to {@link onCertificatesUpdateRequested} every time this event is received. + * + * Can return its result via Promise since Chrome 96. + * @param details The certificates to set. Invalid certificates will be ignored. + * @since Chrome 86 + */ + export function setCertificates(details: SetCertificatesDetails): Promise; + export function setCertificates(details: SetCertificatesDetails, callback: () => void): void; + /** + * Stops the pin request started by the {@link requestPin} function. + * + * Can return its result via Promise since Chrome 96. + * @param details Contains the details about the reason for stopping the request flow. + * @since Chrome 57 + */ + export function stopPinRequest(details: StopPinRequestDetails): Promise; + export function stopPinRequest(details: StopPinRequestDetails, callback: () => void): void; + /** + * This event fires if the certificates set via {@link setCertificates} are insufficient or the browser requests updated information. The extension must call {@link setCertificates} with the updated list of certificates and the received `certificatesRequestId`. + * @since Chrome 86 + */ + export const onCertificatesUpdateRequested: events.Event<(request: CertificatesUpdateRequest) => void>; + /** + * This event fires every time the browser needs to sign a message using a certificate provided by this extension via {@link setCertificates}. + * + * The extension must sign the input data from `request` using the appropriate algorithm and private key and return it by calling {@link reportSignature} with the received `signRequestId`. + * @since Chrome 86 + */ + export const onSignatureRequested: events.Event<(request: SignatureRequest) => void>; + } + + /** + * Use the commands API to add keyboard shortcuts that trigger actions in your extension, for example, an action to open the browser action or send a command to the extension. + * + * Manifest: "commands" + */ + export namespace commands { export interface Command { - /** Optional. The name of the Extension Command */ + /** Optional. The name of the Extension Command */ name?: string | undefined; - /** Optional. The Extension Command description */ + /** Optional. The Extension Command description */ description?: string | undefined; - /** Optional. The shortcut active for this command, or blank if not active. */ + /** Optional. The shortcut active for this command, or blank if not active. */ shortcut?: string | undefined; } - export interface CommandEvent extends Browser.events.Event<(command: string, tab: Browser.tabs.Tab) => void> {} + export interface CommandEvent extends chrome.events.Event<(command: string, tab: chrome.tabs.Tab) => void> { + } /** * Returns all the registered extension commands for this extension and their shortcut (if active). @@ -1495,16 +1936,48 @@ export namespace Browser { * @param callback Called to return the registered commands. */ export function getAll(callback: (commands: Command[]) => void): void; - /** Fired when a registered command is activated using a keyboard shortcut. */ export var onCommand: CommandEvent; + + /** The new description for the command. */ + interface _UpdateDetail { + /** The name of the command. */ + name: string; + /** The new description for the command. */ + description?: string | undefined; + shortcut?: string | undefined; + } + + interface _OnChangedChangeInfo { + /** The name of the shortcut. */ + name: string; + /** The new shortcut active for this command, or blank if not active. */ + newShortcut: string; + /** + * The old shortcut which is no longer active for this command, or blank if the shortcut was previously inactive. + */ + oldShortcut: string; + } + + /** + * Update the details of an already defined command. + * @param detail The new description for the command. + */ + function update(detail: _UpdateDetail): Promise; + /** + * Reset a command's details to what is specified in the manifest. + * @param name The name of the command. + */ + function reset(name: string): Promise; + + /** Fired when a registered command is activated using a keyboard shortcut. */ + const onCommand: WebExtEvent<(command: string) => void>; + /** Fired when a registered command's shortcut is changed. */ + const onChanged: WebExtEvent<(changeInfo: _OnChangedChangeInfo) => void>; } - //////////////////// - // Content Settings - //////////////////// /** - * Use the `Browser.contentSettings` API to change settings that control whether websites can use features such as cookies, JavaScript, and plugins. More generally speaking, content settings allow you to customize Chrome's behavior on a per-site basis instead of globally. + * Use the `chrome.contentSettings` API to change settings that control whether websites can use features such as cookies, JavaScript, and plugins. More generally speaking, content settings allow you to customize Chrome's behavior on a per-site basis instead of globally. * * Permissions: "contentSettings" */ @@ -1512,21 +1985,21 @@ export namespace Browser { /** @since Chrome 113 */ export enum AutoVerifyContentSetting { ALLOW = "allow", - BLOCK = "block", + BLOCK = "block" } /** @since Chrome 46 */ export enum CameraContentSetting { ALLOW = "allow", BLOCK = "block", - ASK = "ask", + ASK = "ask" } /** @since Chrome 121 */ export enum ClipboardContentSetting { ALLOW = "allow", BLOCK = "block", - ASK = "ask", + ASK = "ask" } interface ContentSettingClearParams { @@ -1557,7 +2030,7 @@ export namespace Browser { resourceIdentifier?: ResourceIdentifier; /** Where to set the setting (default: regular). */ scope?: `${Scope}`; - /** The pattern for the secondary URL. Defaults to matching all URLs. For details on the format of a pattern, see Content Setting Patterns.*/ + /** The pattern for the secondary URL. Defaults to matching all URLs. For details on the format of a pattern, see Content Setting Patterns. */ secondaryPattern?: string; /** The setting applied by this rule. See the description of the individual ContentSetting objects for the possible values. */ setting: T; @@ -1571,7 +2044,6 @@ export namespace Browser { */ clear(details: ContentSettingClearParams): Promise; clear(details: ContentSettingClearParams, callback: () => void): void; - /** * Gets the current content setting for a given pair of URLs. * @@ -1579,11 +2051,9 @@ export namespace Browser { */ get(details: ContentSettingGetParams): Promise>; get(details: ContentSettingGetParams, callback: (details: ContentSettingGetResult) => void): void; - /** Can return its result via Promise since Chrome 96. */ getResourceIdentifiers(): Promise; getResourceIdentifiers(callback: (resourceIdentifiers?: ResourceIdentifier[]) => void): void; - /** * Applies a new content setting rule. * @@ -1597,78 +2067,78 @@ export namespace Browser { export enum CookiesContentSetting { ALLOW = "allow", BLOCK = "block", - SESSION_ONLY = "session_only", + SESSION_ONLY = "session_only" } /** @since Chrome 44 */ export enum FullscreenContentSetting { - ALLOW = "allow", + ALLOW = "allow" } /** @since Chrome 44 */ export enum ImagesContentSetting { ALLOW = "allow", - BLOCK = "block", + BLOCK = "block" } /** @since Chrome 44 */ export enum JavascriptContentSetting { ALLOW = "allow", - BLOCK = "block", + BLOCK = "block" } /** @since Chrome 44 */ export enum LocationContentSetting { ALLOW = "allow", BLOCK = "block", - ASK = "ask", + ASK = "ask" } /** @since Chrome 46 */ export enum MicrophoneContentSetting { ALLOW = "allow", BLOCK = "block", - ASK = "ask", + ASK = "ask" } /** @since Chrome 44 */ export enum MouselockContentSetting { - ALLOW = "allow", + ALLOW = "allow" } /** @since Chrome 44 */ export enum MultipleAutomaticDownloadsContentSetting { ALLOW = "allow", BLOCK = "block", - ASK = "ask", + ASK = "ask" } /** @since Chrome 44 */ export enum NotificationsContentSetting { ALLOW = "allow", BLOCK = "block", - ASK = "ask", + ASK = "ask" } /** @since Chrome 44 */ export enum PluginsContentSetting { - BLOCK = "block", + BLOCK = "block" } /** @since Chrome 44 */ export enum PopupsContentSetting { ALLOW = "allow", - BLOCK = "block", + BLOCK = "block" } /** @since Chrome 44 */ export enum PpapiBrokerContentSetting { - BLOCK = "block", + BLOCK = "block" } /** The only content type using resource identifiers is contentSettings.plugins. For more information, see Resource Identifiers. */ export interface ResourceIdentifier { - /** A human readable description of the resource. */ + /** A human readable description of the resource. */ description?: string; /** The resource identifier for the given content type. */ id: string; @@ -1684,7 +2154,7 @@ export namespace Browser { */ export enum Scope { REGULAR = "regular", - INCOGNITO_SESSION_ONLY = "incognito_session_only", + INCOGNITO_SESSION_ONLY = "incognito_session_only" } /** @@ -1701,7 +2171,6 @@ export namespace Browser { * The primary URL is the URL of the top-level frame. The secondary URL is not used. */ export const automaticDownloads: ContentSetting<`${MultipleAutomaticDownloadsContentSetting}`>; - /** * Whether to allow sites to use the Private State Tokens API. One of * @@ -1715,7 +2184,6 @@ export namespace Browser { * @since Chrome 113 */ export const autoVerify: ContentSetting<`${AutoVerifyContentSetting}`>; - /** * Whether to allow sites to access the camera. One of * @@ -1731,7 +2199,6 @@ export namespace Browser { * @since Chrome 46 */ export const camera: ContentSetting<`${CameraContentSetting}`>; - /** * Whether to allow sites to access the clipboard via advanced capabilities of the Async Clipboard API. "Advanced" capabilities include anything besides writing built-in formats after a user gesture, i.e. the ability to read, the ability to write custom formats, and the ability to write without a user gesture. One of * @@ -1747,7 +2214,6 @@ export namespace Browser { * @since Chrome 121 */ export const clipboard: ContentSetting<`${ClipboardContentSetting}`>; - /** * Whether to allow cookies and other local data to be set by websites. One of * @@ -1762,10 +2228,8 @@ export namespace Browser { * The primary URL is the URL representing the cookie origin. The secondary URL is the URL of the top-level frame. */ export const cookies: ContentSetting<`${CookiesContentSetting}`>; - /** @deprecated No longer has any effect. Fullscreen permission is now automatically granted for all sites. Value is always `allow`. */ export const fullscreen: ContentSetting<`${FullscreenContentSetting}`>; - /** * Whether to show images. One of * @@ -1778,7 +2242,6 @@ export namespace Browser { * The primary URL is the URL of the top-level frame. The secondary URL is the URL of the image. */ export const images: ContentSetting<`${ImagesContentSetting}`>; - /** * Whether to run JavaScript. One of * @@ -1791,7 +2254,6 @@ export namespace Browser { * The primary URL is the URL of the top-level frame. The secondary URL is not used. */ export const javascript: ContentSetting<`${JavascriptContentSetting}`>; - /** * Whether to allow Geolocation. One of * @@ -1806,7 +2268,6 @@ export namespace Browser { * The primary URL is the URL of the document which requested location data. The secondary URL is the URL of the top-level frame (which may or may not differ from the requesting URL). */ export const location: ContentSetting<`${LocationContentSetting}`>; - /** * Whether to allow sites to access the microphone. One of * @@ -1822,10 +2283,8 @@ export namespace Browser { * @since Chrome 46 */ export const microphone: ContentSetting<`${MicrophoneContentSetting}`>; - /** @deprecated No longer has any effect. Mouse lock permission is now automatically granted for all sites. Value is always `allow`. */ export const mouselock: ContentSetting<`${MouselockContentSetting}`>; - /** * Whether to allow sites to show desktop notifications. One of * @@ -1840,10 +2299,8 @@ export namespace Browser { * The primary URL is the URL of the document which wants to show the notification. The secondary URL is not used. */ export const notifications: ContentSetting<`${NotificationsContentSetting}`>; - /** @deprecated With Flash support removed in Chrome 88, this permission no longer has any effect. Value is always `block`. Calls to `set()` and `clear()` will be ignored. */ export const plugins: ContentSetting<`${PluginsContentSetting}`>; - /** * Whether to allow sites to show pop-ups. One of * @@ -1856,16 +2313,12 @@ export namespace Browser { * The primary URL is the URL of the top-level frame. The secondary URL is not used. */ export const popups: ContentSetting<`${PopupsContentSetting}`>; - /** @deprecated Previously, controlled whether to allow sites to run plugins unsandboxed, however, with the Flash broker process removed in Chrome 88, this permission no longer has any effect. Value is always `block`. Calls to `set()` and `clear()` will be ignored. */ export const unsandboxedPlugins: ContentSetting<`${PpapiBrokerContentSetting}`>; } - //////////////////// - // Context Menus - //////////////////// /** - * Use the `Browser.contextMenus` API to add items to Google Chrome's context menu. You can choose what types of objects your context menu additions apply to, such as images, hyperlinks, and pages. + * Use the `chrome.contextMenus` API to add items to Google Chrome's context menu. You can choose what types of objects your context menu additions apply to, such as images, hyperlinks, and pages. * * Permissions: "contextMenus" */ @@ -1887,7 +2340,7 @@ export namespace Browser { LAUNCHER = "launcher", BROWSER_ACTION = "browser_action", PAGE_ACTION = "page_action", - ACTION = "action", + ACTION = "action" } /** @@ -1899,7 +2352,7 @@ export namespace Browser { checked?: boolean; /** List of contexts this menu item will appear in. Defaults to `['page']`. */ contexts?: [`${ContextType}`, ...`${ContextType}`[]]; - /** Restricts the item to apply only to documents or frames whose URL matches one of the given patterns. For details on pattern formats, see Match Patterns. */ + /** Restricts the item to apply only to documents or frames whose URL matches one of the given patterns. For details on pattern formats, see Match Patterns. */ documentUrlPatterns?: string[]; /** Whether this context menu item is enabled or disabled. Defaults to `true`. */ enabled?: boolean; @@ -1921,9 +2374,9 @@ export namespace Browser { * @param tab The details of the tab where the click took place. This parameter is not present for platform apps. */ onclick?: ( - info: OnClickData, - tab: tabs.Tab, - ) => void; + info: OnClickData, + tab: tabs.Tab, + ) => void; } /** @@ -1934,7 +2387,7 @@ export namespace Browser { NORMAL = "normal", CHECKBOX = "checkbox", RADIO = "radio", - SEPARATOR = "separator", + SEPARATOR = "separator" } /** Information sent when a context menu item is clicked. */ @@ -1958,7 +2411,7 @@ export namespace Browser { menuItemId: number | string; /** The URL of the page where the menu item was clicked. This property is not set if the click occurred in a context where there is no current page, such as in a launcher context menu. */ pageUrl?: string; - /** The parent ID, if any, for the item clicked.*/ + /** The parent ID, if any, for the item clicked. */ parentMenuItemId?: number | string; /** The text for the context selection, if any. */ selectionText?: string | undefined; @@ -1970,13 +2423,11 @@ export namespace Browser { /** The maximum number of top level extension items that can be added to an extension action context menu. Any items beyond this limit will be ignored. */ export const ACTION_MENU_TOP_LEVEL_LIMIT: 6; - /** - * Creates a new context menu item. If an error occurs during creation, it may not be detected until the creation callback fires; details will be in {@link Browser.runtime.lastError}. + * Creates a new context menu item. If an error occurs during creation, it may not be detected until the creation callback fires; details will be in {@link chrome.runtime.lastError}. * @return The ID of the newly created item. */ export function create(createProperties: CreateProperties, callback?: () => void): number | string; - /** * Removes a context menu item. * @param menuItemId The ID of the context menu item to remove. @@ -1985,7 +2436,6 @@ export namespace Browser { */ export function remove(menuItemId: string | number): Promise; export function remove(menuItemId: string | number, callback: () => void): void; - /** * Removes all context menu items added by this extension. * @@ -1993,7 +2443,6 @@ export namespace Browser { */ export function removeAll(): Promise; export function removeAll(callback: () => void): void; - /** * Updates a previously created context menu item. * @param id The ID of the item to update. @@ -2002,28 +2451,160 @@ export namespace Browser { * Can return its result via Promise since Chrome 123. */ export function update(id: string | number, updateProperties: Omit): Promise; - export function update( - id: string | number, - updateProperties: Omit, - callback: () => void, - ): void; - + export function update(id: string | number, updateProperties: Omit, callback: () => void): void; /** Fired when a context menu item is clicked. */ export const onClicked: events.Event<(info: OnClickData, tab?: tabs.Tab) => void>; + + interface _CreateCreatePropertiesIcons { + [key: number]: string; + } + + interface _CreateCreateProperties { + /** The type of menu item. Defaults to 'normal' if not specified. */ + type?: ItemType | undefined; + /** + * The unique ID to assign to this item. Mandatory for event pages. Cannot be the same as another ID for this extension. + */ + id?: string | undefined; + icons?: _CreateCreatePropertiesIcons | undefined; + /** + * The text to be displayed in the item; this is _required_ unless `type` is 'separator'. When the context is 'selection', you can use `%s` within the string to show the selected text. For example, if this parameter's value is "Translate '%s' to Pig Latin" and the user selects the word "cool", the context menu item for the selection is "Translate 'cool' to Pig Latin". + */ + title?: string | undefined; + /** + * The initial state of a checkbox or radio item: true for selected and false for unselected. Only one radio item can be selected at a time in a given group of radio items. + */ + checked?: boolean | undefined; + /** List of contexts this menu item will appear in. Defaults to ['page'] if not specified. */ + contexts?: ContextType[] | undefined; + /** + * List of view types where the menu item will be shown. Defaults to any view, including those without a viewType. + */ + viewTypes?: extension.ViewType[] | undefined; + /** Whether the item is visible in the menu. */ + visible?: boolean | undefined; + /** + * A function that will be called back when the menu item is clicked. Event pages cannot use this; instead, they should register a listener for `contextMenus.onClicked`. + * @param info Information about the item clicked and the context where the click happened. + * @param tab The details of the tab where the click took place. Note: this parameter only present for extensions. + * Not supported on manifest versions above 2. + */ + onclick?: (info: OnClickData, tab: tabs.Tab) => void | undefined; + /** The ID of a parent menu item; this makes the item a child of a previously added item. */ + parentId?: number | string | undefined; + /** + * Lets you restrict the item to apply only to documents whose URL matches one of the given patterns. (This applies to frames as well.) For details on the format of a pattern, see Match Patterns. + */ + documentUrlPatterns?: string[] | undefined; + /** + * Similar to documentUrlPatterns, but lets you filter based on the src attribute of img/audio/video tags and the href of anchor tags. + */ + targetUrlPatterns?: string[] | undefined; + /** Whether this context menu item is enabled or disabled. Defaults to true. */ + enabled?: boolean | undefined; + /** Specifies a command to issue for the context click. */ + command?: string | _CreateCreatePropertiesCommand | undefined; + } + + interface _UpdateUpdatePropertiesIcons { + [key: number]: string; + } + + /** The properties to update. Accepts the same values as the create function. */ + interface _UpdateUpdateProperties { + type?: ItemType | undefined; + icons?: _UpdateUpdatePropertiesIcons | undefined; + title?: string | undefined; + checked?: boolean | undefined; + contexts?: ContextType[] | undefined; + viewTypes?: extension.ViewType[] | undefined; + /** Whether the item is visible in the menu. */ + visible?: boolean | undefined; + /** + * @param tab The details of the tab where the click took place. Note: this parameter only present for extensions. + * Not supported on manifest versions above 2. + */ + onclick?: (info: OnClickData, tab: tabs.Tab) => void | undefined; + /** Note: You cannot change an item to be a child of one of its own descendants. */ + parentId?: number | string | undefined; + documentUrlPatterns?: string[] | undefined; + targetUrlPatterns?: string[] | undefined; + enabled?: boolean | undefined; + } + + interface _OverrideContextContextOptions { + /** Whether to also include default menu items in the menu. */ + showDefaults?: boolean | undefined; + /** + * ContextType to override, to allow menu items from other extensions in the menu. Currently only 'bookmark' and 'tab' are supported. showDefaults cannot be used with this option. + */ + context?: _OverrideContextContextOptionsContext | undefined; + /** Required when context is 'bookmark'. Requires 'bookmark' permission. */ + bookmarkId?: string | undefined; + /** Required when context is 'tab'. Requires 'tabs' permission. */ + tabId?: number | undefined; + } + + /** + * Information about the context of the menu action and the created menu items. For more information about each property, see OnClickData. The following properties are only set if the extension has host permissions for the given context: linkUrl, linkText, srcUrl, pageUrl, frameUrl, selectionText. + */ + interface _OnShownInfo { + /** A list of IDs of the menu items that were shown. */ + menuIds: Array; + /** A list of all contexts that apply to the menu. */ + contexts: ContextType[]; + viewType?: extension.ViewType | undefined; + editable: boolean; + mediaType?: string | undefined; + linkUrl?: string | undefined; + linkText?: string | undefined; + srcUrl?: string | undefined; + pageUrl?: string | undefined; + frameUrl?: string | undefined; + selectionText?: string | undefined; + targetElementId?: number | undefined; + } + + /** + * Show the matching menu items from this extension instead of the default menu. This should be called during a 'contextmenu' DOM event handler, and only applies to the menu that opens after this event. + */ + function overrideContext(contextOptions: _OverrideContextContextOptions): void; + /** + * Updates the extension items in the shown menu, including changes that have been made since the menu was shown. Has no effect if the menu is hidden. Rebuilding a shown menu is an expensive operation, only invoke this method when necessary. + */ + function refresh(): Promise; + /** + * Retrieve the element that was associated with a recent contextmenu event. + * @param targetElementId The identifier of the clicked element, available as info.targetElementId in the menus.onShown, onClicked or onclick event. + */ + function getTargetElement(targetElementId: number): Element | void; + + const ACTION_MENU_TOP_LEVEL_LIMIT: number; + /** + * Fired when a context menu item is clicked. + * @param info Information about the item clicked and the context where the click happened. + * @param [tab] The details of the tab where the click took place. If the click did not take place in a tab, this parameter will be missing. + */ + const onClicked: WebExtEvent<(info: OnClickData, tab?: tabs.Tab) => void>; + /** + * Fired when a menu is shown. The extension can add, modify or remove menu items and call menus.refresh() to update the menu. + * @param info Information about the context of the menu action and the created menu items. For more information about each property, see OnClickData. The following properties are only set if the extension has host permissions for the given context: linkUrl, linkText, srcUrl, pageUrl, frameUrl, selectionText. + * @param tab The details of the tab where the menu was opened. + */ + const onShown: WebExtEvent<(info: _OnShownInfo, tab: tabs.Tab) => void>; + /** Fired when a menu is hidden. This event is only fired if onShown has fired before. */ + const onHidden: WebExtEvent<() => void>; } - //////////////////// - // Cookies - //////////////////// /** - * Use the `Browser.cookies` API to query and modify cookies, and to be notified when they change. + * Use the `chrome.cookies` API to query and modify cookies, and to be notified when they change. * * Permissions: "cookies" * * Manifest: "host_permissions" */ export namespace cookies { - /** A cookie's 'SameSite' state (https://tools.ietf.org/html/draft-west-first-party-cookies). 'no_restriction' corresponds to a cookie set with 'SameSite=None', 'lax' to 'SameSite=Lax', and 'strict' to 'SameSite=Strict'. 'unspecified' corresponds to a cookie set without the SameSite attribute. **/ + /** A cookie's 'SameSite' state (https://tools.ietf.org/html/draft-west-first-party-cookies). 'no_restriction' corresponds to a cookie set with 'SameSite=None', 'lax' to 'SameSite=Lax', and 'strict' to 'SameSite=Strict'. 'unspecified' corresponds to a cookie set without the SameSite attribute. */ export type SameSiteStatus = "unspecified" | "no_restriction" | "lax" | "strict"; /** Represents information about an HTTP cookie. */ @@ -2045,7 +2626,7 @@ export namespace Browser { session: boolean; /** True if the cookie is a host-only cookie (i.e. a request's host must exactly match the domain of the cookie). */ hostOnly: boolean; - /** Optional. The expiration date of the cookie as the number of seconds since the UNIX epoch. Not provided for session cookies. */ + /** Optional. The expiration date of the cookie as the number of seconds since the UNIX epoch. Not provided for session cookies. */ expirationDate?: number | undefined; /** The path of the cookie. */ path: string; @@ -2080,31 +2661,31 @@ export namespace Browser { } export interface GetAllDetails { - /** Optional. Restricts the retrieved cookies to those whose domains match or are subdomains of this one. */ + /** Optional. Restricts the retrieved cookies to those whose domains match or are subdomains of this one. */ domain?: string | undefined; - /** Optional. Filters the cookies by name. */ + /** Optional. Filters the cookies by name. */ name?: string | undefined; /** * The partition key for reading or modifying cookies with the Partitioned attribute. * @since Chrome 119 */ partitionKey?: CookiePartitionKey | undefined; - /** Optional. Restricts the retrieved cookies to those that would match the given URL. */ + /** Optional. Restricts the retrieved cookies to those that would match the given URL. */ url?: string | undefined; - /** Optional. The cookie store to retrieve cookies from. If omitted, the current execution context's cookie store will be used. */ + /** Optional. The cookie store to retrieve cookies from. If omitted, the current execution context's cookie store will be used. */ storeId?: string | undefined; - /** Optional. Filters out session vs. persistent cookies. */ + /** Optional. Filters out session vs. persistent cookies. */ session?: boolean | undefined; - /** Optional. Restricts the retrieved cookies to those whose path exactly matches this string. */ + /** Optional. Restricts the retrieved cookies to those whose path exactly matches this string. */ path?: string | undefined; - /** Optional. Filters the cookies by their Secure property. */ + /** Optional. Filters the cookies by their Secure property. */ secure?: boolean | undefined; } export interface SetDetails { - /** Optional. The domain of the cookie. If omitted, the cookie becomes a host-only cookie. */ + /** Optional. The domain of the cookie. If omitted, the cookie becomes a host-only cookie. */ domain?: string | undefined; - /** Optional. The name of the cookie. Empty by default if omitted. */ + /** Optional. The name of the cookie. Empty by default if omitted. */ name?: string | undefined; /** * The partition key for reading or modifying cookies with the Partitioned attribute. @@ -2113,17 +2694,17 @@ export namespace Browser { partitionKey?: CookiePartitionKey | undefined; /** The request-URI to associate with the setting of the cookie. This value can affect the default domain and path values of the created cookie. If host permissions for this URL are not specified in the manifest file, the API call will fail. */ url: string; - /** Optional. The ID of the cookie store in which to set the cookie. By default, the cookie is set in the current execution context's cookie store. */ + /** Optional. The ID of the cookie store in which to set the cookie. By default, the cookie is set in the current execution context's cookie store. */ storeId?: string | undefined; - /** Optional. The value of the cookie. Empty by default if omitted. */ + /** Optional. The value of the cookie. Empty by default if omitted. */ value?: string | undefined; - /** Optional. The expiration date of the cookie as the number of seconds since the UNIX epoch. If omitted, the cookie becomes a session cookie. */ + /** Optional. The expiration date of the cookie as the number of seconds since the UNIX epoch. If omitted, the cookie becomes a session cookie. */ expirationDate?: number | undefined; - /** Optional. The path of the cookie. Defaults to the path portion of the url parameter. */ + /** Optional. The path of the cookie. Defaults to the path portion of the url parameter. */ path?: string | undefined; - /** Optional. Whether the cookie should be marked as HttpOnly. Defaults to false. */ + /** Optional. Whether the cookie should be marked as HttpOnly. Defaults to false. */ httpOnly?: boolean | undefined; - /** Optional. Whether the cookie should be marked as Secure. Defaults to false. */ + /** Optional. Whether the cookie should be marked as Secure. Defaults to false. */ secure?: boolean | undefined; /** * Optional. The cookie's same-site status. Defaults to "unspecified", i.e., if omitted, the cookie is set without specifying a SameSite attribute. @@ -2168,135 +2749,266 @@ export namespace Browser { documentId?: string; /** The unique identifier for the frame within the tab. */ frameId?: number; - /* The unique identifier for the tab containing the frame. */ tabId?: number; } - export interface CookieChangedEvent extends Browser.events.Event<(changeInfo: CookieChangeInfo) => void> {} + export interface CookieChangedEvent extends chrome.events.Event<(changeInfo: CookieChangeInfo) => void> { + } /** * Lists all existing cookie stores. * Parameter cookieStores: All the existing cookie stores. */ export function getAllCookieStores(callback: (cookieStores: CookieStore[]) => void): void; - /** * Lists all existing cookie stores. * @return The `getAllCookieStores` method provides its result via callback or returned as a `Promise` (MV3 only). */ export function getAllCookieStores(): Promise; - /** * The partition key for the frame indicated. * Can return its result via Promise in Manifest V3 * @since Chrome 132 */ export function getPartitionKey(details: FrameDetails): Promise<{ partitionKey: CookiePartitionKey }>; - export function getPartitionKey( - details: FrameDetails, - callback: (details: { partitionKey: CookiePartitionKey }) => void, - ): void; - + export function getPartitionKey(details: FrameDetails, callback: (details: { partitionKey: CookiePartitionKey }) => void): void; /** * Retrieves all cookies from a single cookie store that match the given information. The cookies returned will be sorted, with those with the longest path first. If multiple cookies have the same path length, those with the earliest creation time will be first. * @param details Information to filter the cookies being retrieved. * Parameter cookies: All the existing, unexpired cookies that match the given cookie info. */ export function getAll(details: GetAllDetails, callback: (cookies: Cookie[]) => void): void; - /** * Retrieves all cookies from a single cookie store that match the given information. The cookies returned will be sorted, with those with the longest path first. If multiple cookies have the same path length, those with the earliest creation time will be first. * @param details Information to filter the cookies being retrieved. * @return The `getAll` method provides its result via callback or returned as a `Promise` (MV3 only). */ export function getAll(details: GetAllDetails): Promise; - /** * Sets a cookie with the given cookie data; may overwrite equivalent cookies if they exist. * @param details Details about the cookie being set. * @return The `set` method provides its result via callback or returned as a `Promise` (MV3 only). */ export function set(details: SetDetails): Promise; - /** * Sets a cookie with the given cookie data; may overwrite equivalent cookies if they exist. * @param details Details about the cookie being set. - * Optional parameter cookie: Contains details about the cookie that's been set. If setting failed for any reason, this will be "null", and "Browser.runtime.lastError" will be set. + * Optional parameter cookie: Contains details about the cookie that's been set. If setting failed for any reason, this will be "null", and "chrome.runtime.lastError" will be set. */ export function set(details: SetDetails, callback: (cookie: Cookie | null) => void): void; - /** * Deletes a cookie by name. * @param details Information to identify the cookie to remove. * @return The `remove` method provides its result via callback or returned as a `Promise` (MV3 only). */ export function remove(details: CookieDetails): Promise; - /** * Deletes a cookie by name. * @param details Information to identify the cookie to remove. */ export function remove(details: CookieDetails, callback?: (details: CookieDetails) => void): void; - /** * Retrieves information about a single cookie. If more than one cookie of the same name exists for the given URL, the one with the longest path will be returned. For cookies with the same path length, the cookie with the earliest creation time will be returned. * @param details Details to identify the cookie being retrieved. * Parameter cookie: Contains details about the cookie. This parameter is null if no such cookie was found. */ export function get(details: CookieDetails, callback: (cookie: Cookie | null) => void): void; - /** * Retrieves information about a single cookie. If more than one cookie of the same name exists for the given URL, the one with the longest path will be returned. For cookies with the same path length, the cookie with the earliest creation time will be returned. * @param details Details to identify the cookie being retrieved. * @return The `get` method provides its result via callback or returned as a `Promise` (MV3 only). */ export function get(details: CookieDetails): Promise; - /** Fired when a cookie is set or removed. As a special case, note that updating a cookie's properties is implemented as a two step process: the cookie to be updated is first removed entirely, generating a notification with "cause" of "overwrite" . Afterwards, a new cookie is written with the updated values, generating a second notification with "cause" "explicit". */ export var onChanged: CookieChangedEvent; - } - - //////////////////// - // Debugger - //////////////////// - /** - * The `Browser.debugger` API serves as an alternate transport for Chrome's remote debugging protocol. Use `Browser.debugger` to attach to one or more tabs to instrument network interaction, debug JavaScript, mutate the DOM and CSS, and more. Use the {@link Debuggee} `tabId` to target tabs with `sendCommand` and route events by `tabId` from `onEvent` callbacks. - * - * Permissions: "debugger" - */ - export namespace _debugger { - /** Debuggee identifier. Either tabId, extensionId or targetId must be specified */ - export interface Debuggee { - /** The id of the tab which you intend to debug. */ - tabId?: number; - /** The id of the extension which you intend to debug. Attaching to an extension background page is only possible when the `--silent-debugger-extension-api` command-line switch is used. */ - extensionId?: string; - /** The opaque id of the debug target. */ - targetId?: string; - } /** - * Debugger session identifier. One of tabId, extensionId or targetId must be specified. Additionally, an optional sessionId can be provided. If sessionId is specified for arguments sent from {@link onEvent}, it means the event is coming from a child protocol session within the root debuggee session. If sessionId is specified when passed to {@link sendCommand}, it targets a child protocol session within the root debuggee session. - * @since Chrome 125 + * The description of the storage partition of a cookie. This object may be omitted (null) if a cookie is not partitioned. */ - export interface DebuggerSession { - /** The id of the extension which you intend to debug. Attaching to an extension background page is only possible when the `--silent-debugger-extension-api` command-line switch is used.*/ - extensionId?: string; - /** The opaque id of the Chrome DevTools Protocol session. Identifies a child session within the root session identified by tabId, extensionId or targetId. */ - sessionId?: string; - /** The id of the tab which you intend to debug. */ - tabId?: number; - /** The opaque id of the debug target. */ - targetId?: string; + interface PartitionKey { + /** The first-party URL of the cookie, if the cookie is in storage partitioned by the top-level site. */ + topLevelSite?: string | undefined; } - /** + /** Details to identify the cookie being retrieved. */ + interface _GetDetails { + /** + * The URL with which the cookie to retrieve is associated. This argument may be a full URL, in which case any data following the URL path (e.g. the query string) is simply ignored. If host permissions for this URL are not specified in the manifest file, the API call will fail. + */ + url: string; + /** The name of the cookie to retrieve. */ + name: string; + /** + * The ID of the cookie store in which to look for the cookie. By default, the current execution context's cookie store will be used. + */ + storeId?: string | undefined; + /** + * The first-party domain which the cookie to retrieve is associated. This attribute is required if First-Party Isolation is enabled. + */ + firstPartyDomain?: string | undefined; + /** + * The storage partition, if the cookie is part of partitioned storage. By default, only non-partitioned cookies are returned. + */ + partitionKey?: PartitionKey | undefined; + } + + /** Information to filter the cookies being retrieved. */ + interface _GetAllDetails { + /** Restricts the retrieved cookies to those that would match the given URL. */ + url?: string | undefined; + /** Filters the cookies by name. */ + name?: string | undefined; + /** Restricts the retrieved cookies to those whose domains match or are subdomains of this one. */ + domain?: string | undefined; + /** Restricts the retrieved cookies to those whose path exactly matches this string. */ + path?: string | undefined; + /** Filters the cookies by their Secure property. */ + secure?: boolean | undefined; + /** Filters out session vs. persistent cookies. */ + session?: boolean | undefined; + /** + * The cookie store to retrieve cookies from. If omitted, the current execution context's cookie store will be used. + */ + storeId?: string | undefined; + /** + * Restricts the retrieved cookies to those whose first-party domains match this one. This attribute is required if First-Party Isolation is enabled. To not filter by a specific first-party domain, use `null` or `undefined`. + */ + firstPartyDomain?: string | undefined; + /** + * Selects a specific storage partition to look up cookies. Defaults to null, in which case only non-partitioned cookies are retrieved. If an object iis passed, partitioned cookies are also included, and filtered based on the keys present in the given PartitionKey description. An empty object ({}) returns all cookies (partitioned + unpartitioned), a non-empty object (e.g. {topLevelSite: '...'}) only returns cookies whose partition match all given attributes. + */ + partitionKey?: PartitionKey | undefined; + } + + /** Details about the cookie being set. */ + interface _SetDetails { + /** + * The request-URI to associate with the setting of the cookie. This value can affect the default domain and path values of the created cookie. If host permissions for this URL are not specified in the manifest file, the API call will fail. + */ + url: string; + /** The name of the cookie. Empty by default if omitted. */ + name?: string | undefined; + /** The value of the cookie. Empty by default if omitted. */ + value?: string | undefined; + /** The domain of the cookie. If omitted, the cookie becomes a host-only cookie. */ + domain?: string | undefined; + /** The path of the cookie. Defaults to the path portion of the url parameter. */ + path?: string | undefined; + /** Whether the cookie should be marked as Secure. Defaults to false. */ + secure?: boolean | undefined; + /** Whether the cookie should be marked as HttpOnly. Defaults to false. */ + httpOnly?: boolean | undefined; + /** The cookie's same-site status. */ + sameSite?: SameSiteStatus | undefined; + /** + * The expiration date of the cookie as the number of seconds since the UNIX epoch. If omitted, the cookie becomes a session cookie. + */ + expirationDate?: number | undefined; + /** + * The ID of the cookie store in which to set the cookie. By default, the cookie is set in the current execution context's cookie store. + */ + storeId?: string | undefined; + /** + * The first-party domain of the cookie. This attribute is required if First-Party Isolation is enabled. + */ + firstPartyDomain?: string | undefined; + /** + * The storage partition, if the cookie is part of partitioned storage. By default, non-partitioned storage is used. + */ + partitionKey?: PartitionKey | undefined; + } + + /** + * Contains details about the cookie that's been removed. If removal failed for any reason, this will be "null", and `runtime.lastError` will be set. + */ + interface _RemoveReturnDetails { + /** The URL associated with the cookie that's been removed. */ + url: string; + /** The name of the cookie that's been removed. */ + name: string; + /** The ID of the cookie store from which the cookie was removed. */ + storeId: string; + /** The first-party domain associated with the cookie that's been removed. */ + firstPartyDomain: string; + /** The storage partition, if the cookie is part of partitioned storage. null if not partitioned. */ + partitionKey?: PartitionKey | undefined; + } + + /** Information to identify the cookie to remove. */ + interface _RemoveDetails { + /** + * The URL associated with the cookie. If host permissions for this URL are not specified in the manifest file, the API call will fail. + */ + url: string; + /** The name of the cookie to remove. */ + name: string; + /** + * The ID of the cookie store to look in for the cookie. If unspecified, the cookie is looked for by default in the current execution context's cookie store. + */ + storeId?: string | undefined; + /** + * The first-party domain associated with the cookie. This attribute is required if First-Party Isolation is enabled. + */ + firstPartyDomain?: string | undefined; + /** + * The storage partition, if the cookie is part of partitioned storage. By default, non-partitioned storage is used. + */ + partitionKey?: PartitionKey | undefined; + } + + interface _OnChangedChangeInfo { + /** True if a cookie was removed. */ + removed: boolean; + /** Information about the cookie that was set or removed. */ + cookie: Cookie; + /** The underlying reason behind the cookie's change. */ + cause: OnChangedCause; + } + + /** + * Fired when a cookie is set or removed. As a special case, note that updating a cookie's properties is implemented as a two step process: the cookie to be updated is first removed entirely, generating a notification with "cause" of "overwrite" . Afterwards, a new cookie is written with the updated values, generating a second notification with "cause" "explicit". + */ + const onChanged: WebExtEvent<(changeInfo: _OnChangedChangeInfo) => void>; + } + + /** + * The `chrome.debugger` API serves as an alternate transport for Chrome's remote debugging protocol. Use `chrome.debugger` to attach to one or more tabs to instrument network interaction, debug JavaScript, mutate the DOM and CSS, and more. Use the {@link Debuggee} `tabId` to target tabs with `sendCommand` and route events by `tabId` from `onEvent` callbacks. + * + * Permissions: "debugger" + */ + export namespace _debugger { + /** Debuggee identifier. Either tabId, extensionId or targetId must be specified */ + export interface Debuggee { + /** The id of the tab which you intend to debug. */ + tabId?: number; + /** The id of the extension which you intend to debug. Attaching to an extension background page is only possible when the `--silent-debugger-extension-api` command-line switch is used. */ + extensionId?: string; + /** The opaque id of the debug target. */ + targetId?: string; + } + + /** + * Debugger session identifier. One of tabId, extensionId or targetId must be specified. Additionally, an optional sessionId can be provided. If sessionId is specified for arguments sent from {@link onEvent}, it means the event is coming from a child protocol session within the root debuggee session. If sessionId is specified when passed to {@link sendCommand}, it targets a child protocol session within the root debuggee session. + * @since Chrome 125 + */ + export interface DebuggerSession { + /** The id of the extension which you intend to debug. Attaching to an extension background page is only possible when the `--silent-debugger-extension-api` command-line switch is used. */ + extensionId?: string; + /** The opaque id of the Chrome DevTools Protocol session. Identifies a child session within the root session identified by tabId, extensionId or targetId. */ + sessionId?: string; + /** The id of the tab which you intend to debug. */ + tabId?: number; + /** The opaque id of the debug target. */ + targetId?: string; + } + + /** * Connection termination reason. * @since Chrome 44 */ export enum DetachReason { CANCELED_BY_USER = "canceled_by_user", - TARGET_CLOSED = "target_closed", + TARGET_CLOSED = "target_closed" } /** Debug target information */ @@ -2315,7 +3027,7 @@ export namespace Browser { title: string; /** Target URL. */ url: string; - /** Target favicon URL. */ + /** Target favicon URL. */ faviconUrl?: string; } @@ -2327,7 +3039,7 @@ export namespace Browser { BACKGROUND_PAGE = "background_page", OTHER = "other", PAGE = "page", - WORKER = "worker", + WORKER = "worker" } /** @@ -2339,7 +3051,6 @@ export namespace Browser { */ export function attach(target: Debuggee, requiredVersion: string): Promise; export function attach(target: Debuggee, requiredVersion: string, callback: () => void): void; - /** * Detaches debugger from the given target. * @param target Debugging target from which you want to detach. @@ -2348,7 +3059,6 @@ export namespace Browser { */ export function detach(target: Debuggee): Promise; export function detach(target: Debuggee, callback: () => void): void; - /** * Sends given command to the debugging target. * @param target Debugging target to which you want to send the command. @@ -2357,18 +3067,8 @@ export namespace Browser { * * Can return its result via Promise since Chrome 96. */ - export function sendCommand( - target: DebuggerSession, - method: string, - commandParams?: { [key: string]: unknown }, - ): Promise; - export function sendCommand( - target: DebuggerSession, - method: string, - commandParams?: { [key: string]: unknown }, - callback?: (result?: object) => void, - ): void; - + export function sendCommand(target: DebuggerSession, method: string, commandParams?: { [key: string]: unknown }): Promise; + export function sendCommand(target: DebuggerSession, method: string, commandParams?: { [key: string]: unknown }, callback?: (result?: object) => void): void; /** * Returns the list of available debug targets. * @@ -2376,71 +3076,65 @@ export namespace Browser { */ export function getTargets(): Promise; export function getTargets(callback: (result: TargetInfo[]) => void): void; - /** Fired when browser terminates debugging session for the tab. This happens when either the tab is being closed or Chrome DevTools is being invoked for the attached tab. */ - export const onDetach: Browser.events.Event<(source: Debuggee, reason: `${DetachReason}`) => void>; + export const onDetach: chrome.events.Event<(source: Debuggee, reason: `${DetachReason}`) => void>; /** Fired whenever debugging target issues instrumentation event. */ - export const onEvent: Browser.events.Event<(source: DebuggerSession, method: string, params?: object) => void>; + export const onEvent: chrome.events.Event<(source: DebuggerSession, method: string, params?: object) => void>; } - export { _debugger as debugger }; - - //////////////////// - // Declarative Content - //////////////////// /** - * Use the `Browser.declarativeContent` API to take actions depending on the content of a page, without requiring permission to read the page's content. + * Use the `chrome.declarativeContent` API to take actions depending on the content of a page, without requiring permission to read the page's content. * * Permissions: "declarativeContent" */ export namespace declarativeContent { export interface PageStateUrlDetails { - /** Optional. Matches if the host name of the URL contains a specified string. To test whether a host name component has a prefix 'foo', use hostContains: '.foo'. This matches 'www.foobar.com' and 'foo.com', because an implicit dot is added at the beginning of the host name. Similarly, hostContains can be used to match against component suffix ('foo.') and to exactly match against components ('.foo.'). Suffix- and exact-matching for the last components need to be done separately using hostSuffix, because no implicit dot is added at the end of the host name. */ + /** Optional. Matches if the host name of the URL contains a specified string. To test whether a host name component has a prefix 'foo', use hostContains: '.foo'. This matches 'www.foobar.com' and 'foo.com', because an implicit dot is added at the beginning of the host name. Similarly, hostContains can be used to match against component suffix ('foo.') and to exactly match against components ('.foo.'). Suffix- and exact-matching for the last components need to be done separately using hostSuffix, because no implicit dot is added at the end of the host name. */ hostContains?: string | undefined; - /** Optional. Matches if the host name of the URL is equal to a specified string. */ + /** Optional. Matches if the host name of the URL is equal to a specified string. */ hostEquals?: string | undefined; - /** Optional. Matches if the host name of the URL starts with a specified string. */ + /** Optional. Matches if the host name of the URL starts with a specified string. */ hostPrefix?: string | undefined; - /** Optional. Matches if the host name of the URL ends with a specified string. */ + /** Optional. Matches if the host name of the URL ends with a specified string. */ hostSuffix?: string | undefined; - /** Optional. Matches if the path segment of the URL contains a specified string. */ + /** Optional. Matches if the path segment of the URL contains a specified string. */ pathContains?: string | undefined; - /** Optional. Matches if the path segment of the URL is equal to a specified string. */ + /** Optional. Matches if the path segment of the URL is equal to a specified string. */ pathEquals?: string | undefined; - /** Optional. Matches if the path segment of the URL starts with a specified string. */ + /** Optional. Matches if the path segment of the URL starts with a specified string. */ pathPrefix?: string | undefined; - /** Optional. Matches if the path segment of the URL ends with a specified string. */ + /** Optional. Matches if the path segment of the URL ends with a specified string. */ pathSuffix?: string | undefined; - /** Optional. Matches if the query segment of the URL contains a specified string. */ + /** Optional. Matches if the query segment of the URL contains a specified string. */ queryContains?: string | undefined; - /** Optional. Matches if the query segment of the URL is equal to a specified string. */ + /** Optional. Matches if the query segment of the URL is equal to a specified string. */ queryEquals?: string | undefined; - /** Optional. Matches if the query segment of the URL starts with a specified string. */ + /** Optional. Matches if the query segment of the URL starts with a specified string. */ queryPrefix?: string | undefined; - /** Optional. Matches if the query segment of the URL ends with a specified string. */ + /** Optional. Matches if the query segment of the URL ends with a specified string. */ querySuffix?: string | undefined; - /** Optional. Matches if the URL (without fragment identifier) contains a specified string. Port numbers are stripped from the URL if they match the default port number. */ + /** Optional. Matches if the URL (without fragment identifier) contains a specified string. Port numbers are stripped from the URL if they match the default port number. */ urlContains?: string | undefined; - /** Optional. Matches if the URL (without fragment identifier) is equal to a specified string. Port numbers are stripped from the URL if they match the default port number. */ + /** Optional. Matches if the URL (without fragment identifier) is equal to a specified string. Port numbers are stripped from the URL if they match the default port number. */ urlEquals?: string | undefined; - /** Optional. Matches if the URL (without fragment identifier) matches a specified regular expression. Port numbers are stripped from the URL if they match the default port number. The regular expressions use the RE2 syntax. */ + /** Optional. Matches if the URL (without fragment identifier) matches a specified regular expression. Port numbers are stripped from the URL if they match the default port number. The regular expressions use the RE2 syntax. */ urlMatches?: string | undefined; - /** Optional. Matches if the URL without query segment and fragment identifier matches a specified regular expression. Port numbers are stripped from the URL if they match the default port number. The regular expressions use the RE2 syntax. */ + /** Optional. Matches if the URL without query segment and fragment identifier matches a specified regular expression. Port numbers are stripped from the URL if they match the default port number. The regular expressions use the RE2 syntax. */ originAndPathMatches?: string | undefined; - /** Optional. Matches if the URL (without fragment identifier) starts with a specified string. Port numbers are stripped from the URL if they match the default port number. */ + /** Optional. Matches if the URL (without fragment identifier) starts with a specified string. Port numbers are stripped from the URL if they match the default port number. */ urlPrefix?: string | undefined; - /** Optional. Matches if the URL (without fragment identifier) ends with a specified string. Port numbers are stripped from the URL if they match the default port number. */ + /** Optional. Matches if the URL (without fragment identifier) ends with a specified string. Port numbers are stripped from the URL if they match the default port number. */ urlSuffix?: string | undefined; - /** Optional. Matches if the scheme of the URL is equal to any of the schemes specified in the array. */ + /** Optional. Matches if the scheme of the URL is equal to any of the schemes specified in the array. */ schemes?: string[] | undefined; - /** Optional. Matches if the port of the URL is contained in any of the specified port lists. For example [80, 443, [1000, 1200]] matches all requests on port 80, 443 and in the range 1000-1200. */ + /** Optional. Matches if the port of the URL is contained in any of the specified port lists. For example [80, 443, [1000, 1200]] matches all requests on port 80, 443 and in the range 1000-1200. */ ports?: Array | undefined; } export class PageStateMatcherProperties { - /** Optional. Filters URLs for various criteria. See event filtering. All criteria are case sensitive. */ + /** Optional. Filters URLs for various criteria. See event filtering. All criteria are case sensitive. */ pageUrl?: PageStateUrlDetails | 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. */ + /** 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. */ css?: string[] | undefined; /** * Optional. @@ -2459,13 +3153,15 @@ export namespace Browser { * Declarative event action that enables the extension's action while the corresponding conditions are met. * Manifest v3. */ - export class ShowAction {} + export class ShowAction { + } /** * Declarative event action that shows the extension's page action while the corresponding conditions are met. * Manifest v2. */ - export class ShowPageAction {} + export class ShowPageAction { + } /** Declarative event action that changes the icon of the page action while the corresponding conditions are met. */ export class SetIcon { @@ -2473,16 +3169,14 @@ export namespace Browser { } /** Provides the Declarative Event API consisting of addRules, removeRules, and getRules. */ - export interface PageChangedEvent extends Browser.events.Event<() => void> {} + export interface PageChangedEvent extends chrome.events.Event<() => void> { + } export var onPageChanged: PageChangedEvent; } - //////////////////// - // Declarative Web Request - //////////////////// /** - * Use the `Browser.declarativeWebRequest` API to intercept, block, or modify requests in-flight. It is significantly faster than the Browser.webRequest API because you can register rules that are evaluated in the browser rather than the JavaScript engine, which reduces roundtrip latencies and allows higher efficiency. + * Use the `chrome.declarativeWebRequest` API to intercept, block, or modify requests in-flight. It is significantly faster than the chrome.webRequest API because you can register rules that are evaluated in the browser rather than the JavaScript engine, which reduces roundtrip latencies and allows higher efficiency. * * Permissions: "declarativeWebRequest" * @@ -2517,7 +3211,7 @@ export namespace Browser { export interface RequestMatcher { contentType?: string[] | undefined; - url?: Browser.events.UrlFilter | undefined; + url?: chrome.events.UrlFilter | undefined; excludeContentType?: string[] | undefined; excludeResponseHeader?: HeaderFilter[] | undefined; resourceType?: string | undefined; @@ -2528,7 +3222,8 @@ export namespace Browser { lowerPriorityThan: number; } - export interface RedirectToEmptyDocument {} + export interface RedirectToEmptyDocument { + } export interface RedirectRequest { redirectUrl: string; @@ -2554,7 +3249,8 @@ export namespace Browser { modification: ResponseCookie; } - export interface CancelRequest {} + export interface CancelRequest { + } export interface RemoveRequestHeader { name: string; @@ -2580,7 +3276,8 @@ export namespace Browser { from: string; } - export interface RedirectToTransparentImage {} + export interface RedirectToTransparentImage { + } export interface AddRequestCookie { cookie: RequestCookie; @@ -2590,14 +3287,12 @@ export namespace Browser { filter: RequestCookie; } - export interface RequestedEvent extends Browser.events.Event<() => void> {} + export interface RequestedEvent extends chrome.events.Event<() => void> { + } export var onRequest: RequestedEvent; } - //////////////////// - // DesktopCapture - //////////////////// /** * The Desktop Capture API captures the content of the screen, individual windows, or individual tabs. * @@ -2609,26 +3304,20 @@ export namespace Browser { /** True if "audio" is included in parameter sources, and the end user does not uncheck the "Share audio" checkbox. Otherwise false, and in this case, one should not ask for audio stream through getUserMedia call. */ canRequestAudioTrack: boolean; } + /** * Shows desktop media picker UI with the specified set of sources. * @param sources Set of sources that should be shown to the user. * Parameter streamId: An opaque string that can be passed to getUserMedia() API to generate media stream that corresponds to the source selected by the user. If user didn't select any source (i.e. canceled the prompt) then the callback is called with an empty streamId. The created streamId can be used only once and expires after a few seconds when it is not used. */ - export function chooseDesktopMedia( - sources: string[], - callback: (streamId: string, options: StreamOptions) => void, - ): number; + export function chooseDesktopMedia(sources: string[], callback: (streamId: string, options: StreamOptions) => void): number; /** * Shows desktop media picker UI with the specified set of sources. * @param sources Set of sources that should be shown to the user. * @param targetTab Optional tab for which the stream is created. 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 tab.url. * Parameter streamId: An opaque string that can be passed to getUserMedia() API to generate media stream that corresponds to the source selected by the user. If user didn't select any source (i.e. canceled the prompt) then the callback is called with an empty streamId. The created streamId can be used only once and expires after a few seconds when it is not used. */ - export function chooseDesktopMedia( - sources: string[], - targetTab: Browser.tabs.Tab, - callback: (streamId: string, options: StreamOptions) => void, - ): number; + export function chooseDesktopMedia(sources: string[], targetTab: chrome.tabs.Tab, callback: (streamId: string, options: StreamOptions) => void): number; /** * Hides desktop media picker dialog shown by chooseDesktopMedia(). * @param desktopMediaRequestId Id returned by chooseDesktopMedia() @@ -2636,11 +3325,8 @@ export namespace Browser { export function cancelChooseDesktopMedia(desktopMediaRequestId: number): void; } - //////////////////// - // Dev Tools - Inspected Window - //////////////////// /** - * Use the `Browser.devtools.inspectedWindow` API to interact with the inspected window: obtain the tab ID for the inspected page, evaluate the code in the context of the inspected window, reload the page, or obtain the list of resources within the page. + * Use the `chrome.devtools.inspectedWindow` API to interact with the inspected window: obtain the tab ID for the inspected page, evaluate the code in the context of the inspected window, reload the page, or obtain the list of resources within the page. * * Manifest: "devtools_page" */ @@ -2653,38 +3339,32 @@ export namespace Browser { * Gets the content of the resource. * @param callback A function that receives resource content when the request completes. */ - getContent( - callback: ( + getContent(callback: ( /** Content of the resource (potentially encoded) */ content: string, /** Empty if content is not encoded, encoding name otherwise. Currently, only base64 is supported. */ encoding: string, - ) => void, - ): void; + ) => void): void; /** * 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?: ( + setContent(content: string, commit: boolean, callback?: ( /** * Set to undefined if the resource content was set successfully; describes error otherwise. */ error?: object, - ) => void, - ): void; + ) => 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. */ + /** 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. */ 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. */ + /** 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. */ 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. */ + /** 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. */ injectedScript?: string | undefined; /** * Optional. @@ -2709,15 +3389,14 @@ export namespace Browser { value: string; } - export interface ResourceAddedEvent extends Browser.events.Event<(resource: Resource) => void> {} + export interface ResourceAddedEvent extends chrome.events.Event<(resource: Resource) => void> { + } - export interface ResourceContentCommittedEvent - extends Browser.events.Event<(resource: Resource, content: string) => void> - {} + export interface ResourceContentCommittedEvent extends chrome.events.Event<(resource: Resource, content: string) => void> { + } - /** The ID of the tab being inspected. This ID may be used with Browser.tabs.* API. */ + /** The ID of the tab being inspected. This ID may be used with chrome.tabs.* API. */ export var tabId: number; - /** Reloads the inspected page. */ export function reload(reloadOptions?: ReloadOptions): void; /** @@ -2727,10 +3406,7 @@ export namespace Browser { * 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; + 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. * @param expression An expression to evaluate. @@ -2739,17 +3415,12 @@ export namespace Browser { * 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, - options?: EvalOptions, - callback?: (result: T, exceptionInfo: EvaluationExceptionInfo) => void, - ): void; + 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 getResources(callback: (resources: Resource[]) => void): void; - /** Fired when a new resource is added to the inspected page. */ export var onResourceAdded: ResourceAddedEvent; /** Fired when a new revision of the resource is committed (e.g. user saves an edited version of the resource in the Developer Tools). */ @@ -2763,40 +3434,112 @@ export namespace Browser { /** 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; } + + /** An object providing details if an exception occurred while evaluating the expression. */ + interface _EvalReturnExceptionInfo { + /** Set if the error occurred on the DevTools side before the expression is evaluated. */ + isError: boolean; + /** Set if the error occurred on the DevTools side before the expression is evaluated. */ + code: string; + /** Set if the error occurred on the DevTools side before the expression is evaluated. */ + description: string; + /** + * Set if the error occurred on the DevTools side before the expression is evaluated, contains the array of the values that may be substituted into the description string to provide more information about the cause of the error. + */ + details: any[]; + /** Set if the evaluated code produces an unhandled exception. */ + isException: boolean; + /** Set if the evaluated code produces an unhandled exception. */ + value: string; + } + + /** The options parameter can contain one or more options. */ + 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. + * @deprecated Unsupported on Firefox at this time. + */ + 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`. + * @deprecated Unsupported on Firefox at this time. + */ + 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. + * @deprecated Unsupported on Firefox at this time. + */ + contextSecurityOrigin?: string | undefined; + } + + interface _ReloadReloadOptions { + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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 Please avoid using this parameter, it will be removed soon. + */ + preprocessorScript?: string | undefined; + } + + /** The ID of the tab being inspected. This ID may be used with browser.tabs.* API. */ + const tabId: number; + /** + * Fired when a new resource is added to the inspected page. + * @deprecated Unsupported on Firefox at this time. + */ + const onResourceAdded: WebExtEvent<(resource: Resource) => void> | undefined; + /** + * Fired when a new revision of the resource is committed (e.g. user saves an edited version of the resource in the Developer Tools). + * @param content New content of the resource. + * @deprecated Unsupported on Firefox at this time. + */ + const onResourceContentCommitted: WebExtEvent<(resource: Resource, content: string) => void> | undefined; } - //////////////////// - // Dev Tools - Network - //////////////////// /** - * Use the `Browser.devtools.network` API to retrieve the information about network requests displayed by the Developer Tools in the Network panel. + * Use the `chrome.devtools.network` API to retrieve the information about network requests displayed by the Developer Tools in the Network panel. * * Manifest: "devtools_page" */ export namespace devtools.network { /** Represents a HAR entry for a specific finished request. */ - export interface HAREntry extends HARFormatEntry {} + export interface HAREntry extends HARFormatEntry { + } + /** Represents a HAR log that contains all known network requests. */ - export interface HARLog extends HARFormatLog {} + 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 { + export interface Request extends chrome.devtools.network.HAREntry { /** * Returns content of the response body. * @param callback A function that receives the response body when the request completes. */ - getContent( - callback: ( + getContent(callback: ( /** Content of the response body (potentially encoded) */ content: string, /** Empty if content is not encoded, encoding name otherwise. Currently, only base64 is supported */ encoding: string, - ) => void, - ): void; + ) => void): void; } - export interface RequestFinishedEvent extends Browser.events.Event<(request: Request) => void> {} + export interface RequestFinishedEvent extends chrome.events.Event<(request: Request) => void> { + } - export interface NavigatedEvent extends Browser.events.Event<(url: string) => void> {} + export interface NavigatedEvent extends chrome.events.Event<(url: string) => void> { + } /** * Returns HAR log that contains all known network requests. @@ -2804,24 +3547,32 @@ export namespace Browser { * Parameter harLog: A HAR log. See HAR specification for details. */ export function getHAR(callback: (harLog: HARLog) => void): void; - /** Fired when a network request is finished and all request data are available. */ export var onRequestFinished: RequestFinishedEvent; /** Fired when the inspected window navigates to a new page. */ export var onNavigated: NavigatedEvent; + /** + * Fired when a network request is finished and all request data are available. + * @param request Description of a network request in the form of a HAR entry. See HAR specification for details. + */ + const onRequestFinished: WebExtEvent<(request: Request) => void>; + /** + * Fired when the inspected window navigates to a new page. + * @param url URL of the new page. + */ + const onNavigated: WebExtEvent<(url: string) => void>; } - //////////////////// - // Dev Tools - Performance - //////////////////// /** - * Use the `Browser.devtools.performance` API to listen to recording status updates in the Performance panel in DevTools. + * Use the `chrome.devtools.performance` API to listen to recording status updates in the Performance panel in DevTools. * @since Chrome 129 */ export namespace devtools.performance { - export interface ProfilingStartedEvent extends Browser.events.Event<() => void> {} + export interface ProfilingStartedEvent extends chrome.events.Event<() => void> { + } - export interface ProfilingStoppedEvent extends Browser.events.Event<() => void> {} + export interface ProfilingStoppedEvent extends chrome.events.Event<() => void> { + } /** Fired when the Performance panel begins recording performance data. */ export var onProfilingStarted: ProfilingStartedEvent; @@ -2829,23 +3580,29 @@ export namespace Browser { export var onProfilingStopped: ProfilingStoppedEvent; } - //////////////////// - // Dev Tools - Panels - //////////////////// /** - * Use the `Browser.devtools.panels` API to integrate your extension into Developer Tools window UI: create your own panels, access existing panels, and add sidebars. + * Use the `chrome.devtools.panels` API to integrate your extension into Developer Tools window UI: create your own panels, access existing panels, and add sidebars. * * Manifest: "devtools_page" */ export namespace devtools.panels { - export interface PanelShownEvent extends Browser.events.Event<(window: Window) => void> {} + export interface PanelShownEvent extends chrome.events.Event<(window: Window) => void> { + } - export interface PanelHiddenEvent extends Browser.events.Event<() => void> {} + export interface PanelHiddenEvent extends chrome.events.Event<() => void> { + } - export interface PanelSearchEvent extends Browser.events.Event<(action: string, queryString?: string) => void> {} + export interface PanelSearchEvent extends chrome.events.Event<(action: string, queryString?: string) => void> { + } /** Represents a panel created by extension. */ export interface ExtensionPanel { + /** Fired when the user switches to the panel. */ + onShown: PanelShownEvent; + /** Fired when the user switches away from the panel. */ + onHidden: PanelHiddenEvent; + /** Fired upon a search action (start of a new search, search result navigation, or search being canceled). */ + onSearch: PanelSearchEvent; /** * Appends a button to the status bar of the panel. * @param iconPath Path to the icon of the button. The file should contain a 64x24-pixel image composed of two 32x24 icons. The left icon is used when the button is inactive; the right icon is displayed when the button is pressed. @@ -2853,18 +3610,15 @@ export namespace Browser { * @param disabled Whether the button is disabled. */ createStatusBarButton(iconPath: string, tooltipText: string, disabled: boolean): Button; - /** Fired when the user switches to the panel. */ - onShown: PanelShownEvent; - /** Fired when the user switches away from the panel. */ - onHidden: PanelHiddenEvent; - /** Fired upon a search action (start of a new search, search result navigation, or search being canceled). */ - onSearch: PanelSearchEvent; } - export interface ButtonClickedEvent extends Browser.events.Event<() => void> {} + export interface ButtonClickedEvent extends chrome.events.Event<() => void> { + } /** A button created by the extension. */ export interface Button { + /** Fired when the button is clicked. */ + onClicked: ButtonClickedEvent; /** * Updates the attributes of the button. If some of the arguments are omitted or null, the corresponding attributes are not updated. * @param iconPath Path to the new icon of the button. @@ -2872,28 +3626,24 @@ export namespace Browser { * @param disabled Whether the button is disabled. */ update(iconPath?: string | null, tooltipText?: string | null, disabled?: boolean | null): void; - /** Fired when the button is clicked. */ - onClicked: ButtonClickedEvent; } - export interface SelectionChangedEvent extends Browser.events.Event<() => void> {} + export interface SelectionChangedEvent extends chrome.events.Event<() => void> { + } /** Represents the Elements panel. */ export interface ElementsPanel { + /** Fired when an object is selected in the panel. */ + onSelectionChanged: SelectionChangedEvent; /** * 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?: ( + 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; + ) => void): void; } /** @@ -2901,28 +3651,31 @@ export namespace Browser { * Represents the Sources panel. */ export interface SourcesPanel { + /** Fired when an object is selected in the panel. */ + onSelectionChanged: SelectionChangedEvent; /** * 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?: ( + 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; + ) => void): void; } - export interface ExtensionSidebarPaneShownEvent extends Browser.events.Event<(window: Window) => void> {} + export interface ExtensionSidebarPaneShownEvent extends chrome.events.Event<(window: Window) => void> { + } - export interface ExtensionSidebarPaneHiddenEvent extends Browser.events.Event<() => void> {} + export interface ExtensionSidebarPaneHiddenEvent extends chrome.events.Event<() => void> { + } /** A sidebar created by the extension. */ export interface ExtensionSidebarPane { + /** Fired when the sidebar pane becomes visible as a result of user switching to the panel that hosts it. */ + onShown: ExtensionSidebarPaneShownEvent; + /** 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; /** * Sets the height of the sidebar. * @param height A CSS-like size specification, such as '100px' or '12ex'. @@ -2959,10 +3712,6 @@ export namespace Browser { * @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; - /** 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; } /** Elements panel. */ @@ -2972,7 +3721,6 @@ export namespace Browser { * Sources panel. */ export var sources: SourcesPanel; - /** * Creates an extension panel. * @param title Title that is displayed next to the extension icon in the Developer Tools toolbar. @@ -2981,21 +3729,14 @@ export namespace Browser { * @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, - ): void; + export function create(title: string, iconPath: string, pagePath: string, callback?: (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. */ - export function setOpenResourceHandler( - callback?: (resource: Browser.devtools.inspectedWindow.Resource, lineNumber: number) => void, - ): void; + export function setOpenResourceHandler(callback?: (resource: chrome.devtools.inspectedWindow.Resource, lineNumber: number) => void): void; /** * @since Chrome 38 * Requests DevTools to open a URL in a Developer Tools panel. @@ -3012,24 +3753,27 @@ export namespace Browser { * @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, - columnNumber: number, - callback?: (response: unknown) => unknown, - ): void; + export function openResource(url: string, lineNumber: number, columnNumber: number, callback?: (response: unknown) => unknown): void; /** * @since Chrome 59 * The name of the color theme set in user's DevTools settings. */ export var themeName: "default" | "dark"; + /** Elements panel. */ + const elements: ElementsPanel; + /** Sources panel. */ + const sources: SourcesPanel; + /** The name of the current devtools theme. */ + const themeName: string; + /** + * Fired when the devtools theme changes. + * @param themeName The name of the current devtools theme. + */ + const onThemeChanged: WebExtEvent<(themeName: string) => void>; } - //////////////////// - // Dev Tools - Recorder - //////////////////// /** - * Use the `Browser.devtools.recorder` API to customize the Recorder panel in DevTools. + * Use the `chrome.devtools.recorder` API to customize the Recorder panel in DevTools. * @since Chrome 105 */ export namespace devtools.recorder { @@ -3042,13 +3786,11 @@ export namespace Browser { * @since Chrome 112 */ replay?(recording: { [key: string]: unknown }): void; - /** * Converts a recording from the Recorder panel format into a string. * @param recording A recording of the user interaction with the page. This should match [Puppeteer's recording schema](https://github.com/puppeteer/replay/blob/main/docs/api/interfaces/Schema.UserFlow.md). */ stringify?(recording: { [key: string]: unknown }): void; - /** * Converts a step of the recording from the Recorder panel format into a string. * @param step A step of the recording of a user interaction with the page. This should match [Puppeteer's step schema](https://github.com/puppeteer/replay/blob/main/docs/api/modules/Schema.md#step). @@ -3076,25 +3818,17 @@ export namespace Browser { * @since Chrome 112 */ export function createView(title: string, pagePath: string): RecorderView; - /** * Registers a Recorder extension plugin. * @param plugin An instance implementing the RecorderExtensionPlugin interface. * @param name The name of the plugin. * @param mediaType The media type of the string content that the plugin produces. */ - export function registerRecorderExtensionPlugin( - plugin: RecorderExtensionPlugin, - name: string, - mediaType: string, - ): void; + export function registerRecorderExtensionPlugin(plugin: RecorderExtensionPlugin, name: string, mediaType: string): void; } - //////////////////// - // Document Scan - //////////////////// /** - * Use the `Browser.documentScan` API to discover and retrieve images from attached document scanners. + * Use the `chrome.documentScan` API to discover and retrieve images from attached document scanners. * The Document Scan API is designed to allow apps and extensions to view the content of paper documents on an attached document scanner. * * Permissions: "documentScan" @@ -3128,7 +3862,7 @@ export namespace Browser { /** The option can be set in software. */ SOFTWARE_CONFIGURABLE = "SOFTWARE_CONFIGURABLE", /** The option can be set by the user toggling or pushing a button on the scanner. */ - HARDWARE_CONFIGURABLE = "HARDWARE_CONFIGURABLE", + HARDWARE_CONFIGURABLE = "HARDWARE_CONFIGURABLE" } /** @@ -3138,7 +3872,7 @@ export namespace Browser { export enum ConnectionType { UNSPECIFIED = "UNSPECIFIED", USB = "USB", - NETWORK = "NETWORK", + NETWORK = "NETWORK" } /** @@ -3155,7 +3889,7 @@ export namespace Browser { /** The constraint on a specific list of `OptionType.FIXED` values. The `OptionConstraint.list` property will contain `double` values, and the other properties will be unset. */ FIXED_LIST = "FIXED_LIST", /** The constraint on a specific list of `OptionType.STRING` values. The `OptionConstraint.list` property will contain `DOMString` values, and the other properties will be unset. */ - STRING_LIST = "STRING_LIST", + STRING_LIST = "STRING_LIST" } /** @since Chrome 125 */ @@ -3203,7 +3937,7 @@ export namespace Browser { export enum OperationResult { /** An unknown or generic failure occurred. */ UNKNOWN = "UNKNOWN", - /**The operation succeeded. */ + /** The operation succeeded. */ SUCCESS = "SUCCESS", /** The operation is not supported. */ UNSUPPORTED = "UNSUPPORTED", @@ -3234,7 +3968,7 @@ export namespace Browser { /** The device is disconnected. */ MISSING = "MISSING", /** An error has occurred somewhere other than the calling application. */ - INTERNAL_ERROR = "INTERNAL_ERROR", + INTERNAL_ERROR = "INTERNAL_ERROR" } /** @since Chrome 125 */ @@ -3282,7 +4016,7 @@ export namespace Browser { /** An option of this type has no value. Instead, setting an option of this type causes an option-specific side effect in the scanner driver. For example, a button-typed option could be used by a scanner driver to provide a means to select default values or to tell an automatic document feeder to advance to the next sheet of paper. */ BUTTON = "BUTTON", /** Grouping option. No value. This is included for compatibility, but will not normally be returned in `ScannerOption` values. Use `getOptionGroups()` to retrieve the list of groups with their member options. */ - GROUP = "GROUP", + GROUP = "GROUP" } /** @@ -3303,7 +4037,7 @@ export namespace Browser { /** The value is a percent, for example, brightness. */ PERCENT = "PERCENT", /** The value is measured in microseconds, for example, exposure time. */ - MICROSECOND = "MICROSECOND", + MICROSECOND = "MICROSECOND" } /** @since Chrome 125 */ @@ -3431,51 +4165,34 @@ export namespace Browser { */ export function cancelScan(job: T): Promise>; export function cancelScan(job: T, callback: (response: CancelScanResponse) => void): void; - /** * Closes the scanner with the passed in handle and returns a Promise that resolves with a {@link CloseScannerResponse} object. If a callback is used, the object is passed to it instead. Even if the response is not a success, the supplied handle becomes invalid and should not be used for further operations. * @param scannerHandle Specifies the handle of an open scanner that was previously returned from a call to {@link openScanner}. * @since Chrome 125 */ export function closeScanner(scannerHandle: T): Promise>; - export function closeScanner( - scannerHandle: T, - callback: (response: CloseScannerResponse) => void, - ): void; - + export function closeScanner(scannerHandle: T, callback: (response: CloseScannerResponse) => void): void; /** * Gets the group names and member options from a scanner previously opened by {@link openScanner}. This method returns a Promise that resolves with a {@link GetOptionGroupsResponse} object. If a callback is passed to this function, returned data is passed to it instead. * @param scannerHandle The handle of an open scanner returned from a call to {@link openScanner}. * @since Chrome 125 */ export function getOptionGroups(scannerHandle: T): Promise>; - export function getOptionGroups( - scannerHandle: T, - callback: (response: GetOptionGroupsResponse) => void, - ): void; - + export function getOptionGroups(scannerHandle: T, callback: (response: GetOptionGroupsResponse) => void): void; /** * Gets the list of available scanners and returns a Promise that resolves with a {@link GetScannerListResponse} object. If a callback is passed to this function, returned data is passed to it instead. * @param filter A {@link DeviceFilter} indicating which types of scanners should be returned. * @since Chrome 125 */ export function getScannerList(filter: DeviceFilter): Promise; - export function getScannerList( - filter: DeviceFilter, - callback: (response: GetScannerListResponse) => void, - ): void; - + export function getScannerList(filter: DeviceFilter, callback: (response: GetScannerListResponse) => void): void; /** * Opens a scanner for exclusive access and returns a Promise that resolves with an {@link OpenScannerResponse} object. If a callback is passed to this function, returned data is passed to it instead. * @param scannerId The ID of a scanner to be opened. This value is one returned from a previous call to {@link getScannerList}. * @since Chrome 125 */ export function openScanner(scannerId: T): Promise>; - export function openScanner( - scannerId: T, - callback: (response: OpenScannerResponse) => void, - ): void; - + export function openScanner(scannerId: T, callback: (response: OpenScannerResponse) => void): void; /** * Reads the next chunk of available image data from an active job handle, and returns a Promise that resolves with a {@link ReadScanDataResponse} object. If a callback is used, the object is passed to it instead. * @@ -3487,52 +4204,32 @@ export namespace Browser { */ export function readScanData(job: T): Promise>; export function readScanData(job: T, callback: (response: ReadScanDataResponse) => void): void; - /** * Performs a document scan and returns a Promise that resolves with a {@link ScanResults} object. If a callback is passed to this function, the returned data is passed to it instead. * @param options An object containing scan parameters. */ export function scan(options: ScanOptions): Promise; export function scan(options: ScanOptions, callback: (result: ScanResults) => void): void; - /** * Sets options on the specified scanner and returns a Promise that resolves with a {@link SetOptionsResponse} object containing the result of trying to set every value in the order of the passed-in {@link OptionSetting} object. If a callback is used, the object is passed to it instead. * @param scannerHandle The handle of the scanner to set options on. This should be a value previously returned from a call to {@link openScanner}. * @param options A list of `OptionSetting` objects to be applied to the scanner. * @since Chrome 125 */ - export function setOptions( - scannerHandle: T, - options: OptionSetting[], - ): Promise>; - export function setOptions( - scannerHandle: T, - options: OptionSetting[], - callback: (response: SetOptionsResponse) => void, - ): void; - + export function setOptions(scannerHandle: T, options: OptionSetting[]): Promise>; + export function setOptions(scannerHandle: T, options: OptionSetting[], callback: (response: SetOptionsResponse) => void): void; /** * Starts a scan on the specified scanner and returns a Promise that resolves with a {@link StartScanResponse}. If a callback is used, the object is passed to it instead. If the call was successful, the response includes a job handle that can be used in subsequent calls to read scan data or cancel a scan. * @param scannerHandle The handle of an open scanner. This should be a value previously returned from a call to {@link openScanner}. * @param options A {@link StartScanOptions} object indicating the options to be used for the scan. The `StartScanOptions.format` property must match one of the entries returned in the scanner's `ScannerInfo`. * @since Chrome 125 */ - export function startScan( - scannerHandle: T, - options: StartScanOptions, - ): Promise>; - export function startScan( - scannerHandle: T, - options: StartScanOptions, - callback: (response: StartScanResponse) => void, - ): void; + export function startScan(scannerHandle: T, options: StartScanOptions): Promise>; + export function startScan(scannerHandle: T, options: StartScanOptions, callback: (response: StartScanResponse) => void): void; } - //////////////////// - // DOM - //////////////////// /** - * Use the `Browser.dom` API to access special DOM APIs for Extensions + * Use the `chrome.dom` API to access special DOM APIs for Extensions * @since Chrome 88 */ export namespace dom { @@ -3544,11 +4241,8 @@ export namespace Browser { export function openOrClosedShadowRoot(element: HTMLElement): ShadowRoot | null; } - //////////////////// - // Downloads - //////////////////// /** - * Use the `Browser.downloads` API to programmatically initiate, monitor, manipulate, and search for downloads. + * Use the `chrome.downloads` API to programmatically initiate, monitor, manipulate, and search for downloads. * * Permissions: "downloads" */ @@ -3563,55 +4257,55 @@ export namespace Browser { export type FilenameConflictAction = "uniquify" | "overwrite" | "prompt"; export interface DownloadOptions { - /** Optional. Post body. */ + /** Optional. Post body. */ body?: string | undefined; - /** Optional. Use a file-chooser to allow the user to select a filename regardless of whether filename is set or already exists. */ + /** Optional. Use a file-chooser to allow the user to select a filename regardless of whether filename is set or already exists. */ saveAs?: boolean | undefined; /** The URL to download. */ url: string; - /** Optional. A file path relative to the Downloads directory to contain the downloaded file, possibly containing subdirectories. Absolute paths, empty paths, and paths containing back-references ".." will cause an error. onDeterminingFilename allows suggesting a filename after the file's MIME type and a tentative filename have been determined. */ + /** Optional. A file path relative to the Downloads directory to contain the downloaded file, possibly containing subdirectories. Absolute paths, empty paths, and paths containing back-references ".." will cause an error. onDeterminingFilename allows suggesting a filename after the file's MIME type and a tentative filename have been determined. */ filename?: string | undefined; - /** Optional. Extra HTTP headers to send with the request if the URL uses the HTTP[s] protocol. Each header is represented as a dictionary containing the keys name and either value or binaryValue, restricted to those allowed by XMLHttpRequest. */ + /** Optional. Extra HTTP headers to send with the request if the URL uses the HTTP[s] protocol. Each header is represented as a dictionary containing the keys name and either value or binaryValue, restricted to those allowed by XMLHttpRequest. */ headers?: HeaderNameValuePair[] | undefined; - /** Optional. The HTTP method to use if the URL uses the HTTP[S] protocol. */ + /** Optional. The HTTP method to use if the URL uses the HTTP[S] protocol. */ method?: "GET" | "POST" | undefined; - /** Optional. The action to take if filename already exists. */ + /** Optional. The action to take if filename already exists. */ conflictAction?: FilenameConflictAction | undefined; } export interface DownloadDelta { /** The id of the DownloadItem that changed. */ id: number; - /** Optional. The change in danger, if any. */ + /** Optional. The change in danger, if any. */ danger?: StringDelta | undefined; - /** Optional. The change in url, if any. */ + /** Optional. The change in url, if any. */ url?: StringDelta | undefined; /** * Optional. The change in finalUrl, if any. * @since Chrome 54 */ finalUrl?: StringDelta | undefined; - /** Optional. The change in totalBytes, if any. */ + /** Optional. The change in totalBytes, if any. */ totalBytes?: DoubleDelta | undefined; - /** Optional. The change in filename, if any. */ + /** Optional. The change in filename, if any. */ filename?: StringDelta | undefined; - /** Optional. The change in paused, if any. */ + /** Optional. The change in paused, if any. */ paused?: BooleanDelta | undefined; - /** Optional. The change in state, if any. */ + /** Optional. The change in state, if any. */ state?: StringDelta | undefined; - /** Optional. The change in mime, if any. */ + /** Optional. The change in mime, if any. */ mime?: StringDelta | undefined; - /** Optional. The change in fileSize, if any. */ + /** Optional. The change in fileSize, if any. */ fileSize?: DoubleDelta | undefined; - /** Optional. The change in startTime, if any. */ + /** Optional. The change in startTime, if any. */ startTime?: StringDelta | undefined; - /** Optional. The change in error, if any. */ + /** Optional. The change in error, if any. */ error?: StringDelta | undefined; - /** Optional. The change in endTime, if any. */ + /** Optional. The change in endTime, if any. */ endTime?: StringDelta | undefined; - /** Optional. The change in canResume, if any. */ + /** Optional. The change in canResume, if any. */ canResume?: BooleanDelta | undefined; - /** Optional. The change in exists, if any. */ + /** Optional. The change in exists, if any. */ exists?: BooleanDelta | undefined; } @@ -3631,39 +4325,36 @@ export namespace Browser { previous?: string | undefined; } - export type DownloadInterruptReason = - | "FILE_FAILED" - | "FILE_ACCESS_DENIED" - | "FILE_NO_SPACE" - | "FILE_NAME_TOO_LONG" - | "FILE_TOO_LARGE" - | "FILE_VIRUS_INFECTED" - | "FILE_TRANSIENT_ERROR" - | "FILE_BLOCKED" - | "FILE_SECURITY_CHECK_FAILED" - | "FILE_TOO_SHORT" - | "FILE_HASH_MISMATCH" - | "FILE_SAME_AS_SOURCE" - | "NETWORK_FAILED" - | "NETWORK_TIMEOUT" - | "NETWORK_DISCONNECTED" - | "NETWORK_SERVER_DOWN" - | "NETWORK_INVALID_REQUEST" - | "SERVER_FAILED" - | "SERVER_NO_RANGE" - | "SERVER_BAD_CONTENT" - | "SERVER_UNAUTHORIZED" - | "SERVER_CERT_PROBLEM" - | "SERVER_FORBIDDEN" - | "SERVER_UNREACHABLE" - | "SERVER_CONTENT_LENGTH_MISMATCH" - | "SERVER_CROSS_ORIGIN_REDIRECT" - | "USER_CANCELED" - | "USER_SHUTDOWN" - | "CRASH"; - + export type DownloadInterruptReason = | "FILE_FAILED" + | "FILE_ACCESS_DENIED" + | "FILE_NO_SPACE" + | "FILE_NAME_TOO_LONG" + | "FILE_TOO_LARGE" + | "FILE_VIRUS_INFECTED" + | "FILE_TRANSIENT_ERROR" + | "FILE_BLOCKED" + | "FILE_SECURITY_CHECK_FAILED" + | "FILE_TOO_SHORT" + | "FILE_HASH_MISMATCH" + | "FILE_SAME_AS_SOURCE" + | "NETWORK_FAILED" + | "NETWORK_TIMEOUT" + | "NETWORK_DISCONNECTED" + | "NETWORK_SERVER_DOWN" + | "NETWORK_INVALID_REQUEST" + | "SERVER_FAILED" + | "SERVER_NO_RANGE" + | "SERVER_BAD_CONTENT" + | "SERVER_UNAUTHORIZED" + | "SERVER_CERT_PROBLEM" + | "SERVER_FORBIDDEN" + | "SERVER_UNREACHABLE" + | "SERVER_CONTENT_LENGTH_MISMATCH" + | "SERVER_CROSS_ORIGIN_REDIRECT" + | "USER_CANCELED" + | "USER_SHUTDOWN" + | "CRASH"; export type DownloadState = "in_progress" | "interrupted" | "complete"; - export type DangerType = "file" | "url" | "content" | "uncommon" | "host" | "unwanted" | "safe" | "accepted"; export interface DownloadItem { @@ -3690,11 +4381,11 @@ export namespace Browser { mime: string; /** Number of bytes in the whole file post-decompression, or -1 if unknown. */ fileSize: number; - /** The time when the download began in ISO 8601 format. May be passed directly to the Date constructor: Browser.downloads.search({}, function(items){items.forEach(function(item){console.log(new Date(item.startTime))})}) */ + /** The time when the download began in ISO 8601 format. May be passed directly to the Date constructor: chrome.downloads.search({}, function(items){items.forEach(function(item){console.log(new Date(item.startTime))})}) */ startTime: string; - /** Optional. Why the download was interrupted. Several kinds of HTTP errors may be grouped under one of the errors beginning with SERVER_. Errors relating to the network begin with NETWORK_, errors relating to the process of writing the file to the file system begin with FILE_, and interruptions initiated by the user begin with USER_. */ + /** Optional. Why the download was interrupted. Several kinds of HTTP errors may be grouped under one of the errors beginning with SERVER_. Errors relating to the network begin with NETWORK_, errors relating to the process of writing the file to the file system begin with FILE_, and interruptions initiated by the user begin with USER_. */ error?: DownloadInterruptReason | undefined; - /** Optional. The time when the download ended in ISO 8601 format. May be passed directly to the Date constructor: Browser.downloads.search({}, function(items){items.forEach(function(item){if (item.endTime) console.log(new Date(item.endTime))})}) */ + /** Optional. The time when the download ended in ISO 8601 format. May be passed directly to the Date constructor: chrome.downloads.search({}, function(items){items.forEach(function(item){if (item.endTime) console.log(new Date(item.endTime))})}) */ endTime?: string | undefined; /** An identifier that is persistent across browser sessions. */ id: number; @@ -3702,81 +4393,80 @@ export namespace Browser { incognito: boolean; /** Absolute URL. */ referrer: string; - /** Optional. Estimated time when the download will complete in ISO 8601 format. May be passed directly to the Date constructor: Browser.downloads.search({}, function(items){items.forEach(function(item){if (item.estimatedEndTime) console.log(new Date(item.estimatedEndTime))})}) */ + /** Optional. Estimated time when the download will complete in ISO 8601 format. May be passed directly to the Date constructor: chrome.downloads.search({}, function(items){items.forEach(function(item){if (item.estimatedEndTime) console.log(new Date(item.estimatedEndTime))})}) */ estimatedEndTime?: string | undefined; /** True if the download is in progress and paused, or else if it is interrupted and can be resumed starting from where it was interrupted. */ canResume: boolean; /** Whether the downloaded file still exists. This information may be out of date because Chrome does not automatically watch for file removal. Call search() in order to trigger the check for file existence. When the existence check completes, if the file has been deleted, then an onChanged event will fire. Note that search() does not wait for the existence check to finish before returning, so results from search() may not accurately reflect the file system. Also, search() may be called as often as necessary, but will not check for file existence any more frequently than once every 10 seconds. */ exists: boolean; - /** Optional. The identifier for the extension that initiated this download if this download was initiated by an extension. Does not change once it is set. */ + /** Optional. The identifier for the extension that initiated this download if this download was initiated by an extension. Does not change once it is set. */ byExtensionId?: string | undefined; - /** Optional. The localized name of the extension that initiated this download if this download was initiated by an extension. May change if the extension changes its name or if the user changes their locale. */ + /** Optional. The localized name of the extension that initiated this download if this download was initiated by an extension. May change if the extension changes its name or if the user changes their locale. */ byExtensionName?: string | undefined; } export interface GetFileIconOptions { - /** Optional. * The size of the returned icon. The icon will be square with dimensions size * size pixels. The default and largest size for the icon is 32x32 pixels. The only supported sizes are 16 and 32. It is an error to specify any other size. - */ + /** Optional. * The size of the returned icon. The icon will be square with dimensions size * size pixels. The default and largest size for the icon is 32x32 pixels. The only supported sizes are 16 and 32. It is an error to specify any other size. */ size?: 16 | 32 | undefined; } export interface DownloadQuery { - /** Optional. Set elements of this array to DownloadItem properties in order to sort search results. For example, setting orderBy=['startTime'] sorts the DownloadItem by their start time in ascending order. To specify descending order, prefix with a hyphen: '-startTime'. */ + /** Optional. Set elements of this array to DownloadItem properties in order to sort search results. For example, setting orderBy=['startTime'] sorts the DownloadItem by their start time in ascending order. To specify descending order, prefix with a hyphen: '-startTime'. */ orderBy?: string[] | undefined; - /** Optional. Limits results to DownloadItem whose url matches the given regular expression. */ + /** Optional. Limits results to DownloadItem whose url matches the given regular expression. */ urlRegex?: string | undefined; - /** Optional. Limits results to DownloadItem that ended before the time in ISO 8601 format. */ + /** Optional. Limits results to DownloadItem that ended before the time in ISO 8601 format. */ endedBefore?: string | undefined; - /** Optional. Limits results to DownloadItem whose totalBytes is greater than the given integer. */ + /** Optional. Limits results to DownloadItem whose totalBytes is greater than the given integer. */ totalBytesGreater?: number | undefined; - /** Optional. Indication of whether this download is thought to be safe or known to be suspicious. */ + /** Optional. Indication of whether this download is thought to be safe or known to be suspicious. */ danger?: string | undefined; - /** Optional. Number of bytes in the whole file, without considering file compression, or -1 if unknown. */ + /** Optional. Number of bytes in the whole file, without considering file compression, or -1 if unknown. */ totalBytes?: number | undefined; - /** Optional. True if the download has stopped reading data from the host, but kept the connection open. */ + /** Optional. True if the download has stopped reading data from the host, but kept the connection open. */ paused?: boolean | undefined; - /** Optional. Limits results to DownloadItem whose filename matches the given regular expression. */ + /** Optional. Limits results to DownloadItem whose filename matches the given regular expression. */ filenameRegex?: string | undefined; - /** Optional. This array of search terms limits results to DownloadItem whose filename or url contain all of the search terms that do not begin with a dash '-' and none of the search terms that do begin with a dash. */ + /** Optional. This array of search terms limits results to DownloadItem whose filename or url contain all of the search terms that do not begin with a dash '-' and none of the search terms that do begin with a dash. */ query?: string[] | undefined; - /** Optional. Limits results to DownloadItem whose totalBytes is less than the given integer. */ + /** Optional. Limits results to DownloadItem whose totalBytes is less than the given integer. */ totalBytesLess?: number | undefined; - /** Optional. The id of the DownloadItem to query. */ + /** Optional. The id of the DownloadItem to query. */ id?: number | undefined; - /** Optional. Number of bytes received so far from the host, without considering file compression. */ + /** Optional. Number of bytes received so far from the host, without considering file compression. */ bytesReceived?: number | undefined; - /** Optional. Limits results to DownloadItem that ended after the time in ISO 8601 format. */ + /** Optional. Limits results to DownloadItem that ended after the time in ISO 8601 format. */ endedAfter?: string | undefined; - /** Optional. Absolute local path. */ + /** Optional. Absolute local path. */ filename?: string | undefined; - /** Optional. Indicates whether the download is progressing, interrupted, or complete. */ + /** Optional. Indicates whether the download is progressing, interrupted, or complete. */ state?: string | undefined; - /** Optional. Limits results to DownloadItem that started after the time in ISO 8601 format. */ + /** Optional. Limits results to DownloadItem that started after the time in ISO 8601 format. */ startedAfter?: string | undefined; - /** Optional. The file's MIME type. */ + /** Optional. The file's MIME type. */ mime?: string | undefined; - /** Optional. Number of bytes in the whole file post-decompression, or -1 if unknown. */ + /** Optional. Number of bytes in the whole file post-decompression, or -1 if unknown. */ fileSize?: number | undefined; - /** Optional. The time when the download began in ISO 8601 format. */ + /** Optional. The time when the download began in ISO 8601 format. */ startTime?: string | undefined; - /** Optional. Absolute URL. */ + /** Optional. Absolute URL. */ url?: string | undefined; - /** Optional. Limits results to DownloadItem that started before the time in ISO 8601 format. */ + /** Optional. Limits results to DownloadItem that started before the time in ISO 8601 format. */ startedBefore?: string | undefined; - /** Optional. The maximum number of matching DownloadItem returned. Defaults to 1000. Set to 0 in order to return all matching DownloadItem. See search for how to page through results. */ + /** Optional. The maximum number of matching DownloadItem returned. Defaults to 1000. Set to 0 in order to return all matching DownloadItem. See search for how to page through results. */ limit?: number | undefined; - /** Optional. Why a download was interrupted. */ + /** Optional. Why a download was interrupted. */ error?: number | undefined; - /** Optional. The time when the download ended in ISO 8601 format. */ + /** Optional. The time when the download ended in ISO 8601 format. */ endTime?: string | undefined; - /** Optional. Whether the downloaded file exists; */ + /** Optional. Whether the downloaded file exists; */ exists?: boolean | undefined; } export interface DownloadFilenameSuggestion { /** The DownloadItem's new target DownloadItem.filename, as a path relative to the user's default Downloads directory, possibly containing subdirectories. Absolute paths, empty paths, and paths containing back-references ".." will be ignored. */ filename: string; - /** Optional. The action to take if filename already exists. */ + /** Optional. The action to take if filename already exists. */ conflictAction?: string | undefined; } @@ -3785,17 +4475,19 @@ export namespace Browser { enabled: boolean; } - export interface DownloadChangedEvent extends Browser.events.Event<(downloadDelta: DownloadDelta) => void> {} + export interface DownloadChangedEvent extends chrome.events.Event<(downloadDelta: DownloadDelta) => void> { + } - export interface DownloadCreatedEvent extends Browser.events.Event<(downloadItem: DownloadItem) => void> {} + export interface DownloadCreatedEvent extends chrome.events.Event<(downloadItem: DownloadItem) => void> { + } - export interface DownloadErasedEvent extends Browser.events.Event<(downloadId: number) => void> {} + export interface DownloadErasedEvent extends chrome.events.Event<(downloadId: number) => void> { + } - export interface DownloadDeterminingFilenameEvent extends - Browser.events.Event< - (downloadItem: DownloadItem, suggest: (suggestion?: DownloadFilenameSuggestion) => void) => void - > - {} + export interface DownloadDeterminingFilenameEvent extends chrome.events.Event< + (downloadItem: DownloadItem, suggest: (suggestion?: DownloadFilenameSuggestion) => void) => void + > { + } /** * Find DownloadItem. Set query to the empty object to get all DownloadItem. To get a specific DownloadItem, set only the id field. To page through a large number of items, set orderBy: ['-startTime'], set limit to the number of items per page, and set startedAfter to the startTime of the last item from the last page. @@ -3835,11 +4527,7 @@ export namespace Browser { * @param downloadId The identifier for the download. * @param callback A URL to an image that represents the download. */ - export function getFileIcon( - downloadId: number, - options: GetFileIconOptions, - callback: (iconURL: string) => void, - ): void; + export function getFileIcon(downloadId: number, options: GetFileIconOptions, callback: (iconURL: string) => void): void; /** * Resume a paused download. If the request was successful the download is in progress and unpaused. Otherwise runtime.lastError contains an error message. The request will fail if the download is not active. * @param downloadId The id of the download to resume. @@ -3935,7 +4623,6 @@ export namespace Browser { * @since Chrome 105 */ export function setUiOptions(options: UiOptions, callback: () => void): void; - /** When any of a DownloadItem's properties except bytesReceived and estimatedEndTime changes, this event fires with the downloadId and an object containing the properties that changed. */ export var onChanged: DownloadChangedEvent; /** This event fires with the DownloadItem object when a download begins. */ @@ -3944,18 +4631,99 @@ export namespace Browser { export var onErased: DownloadErasedEvent; /** During the filename determination process, extensions will be given the opportunity to override the target DownloadItem.filename. Each extension may not register more than one listener for this event. Each listener must call suggest exactly once, either synchronously or asynchronously. If the listener calls suggest asynchronously, then it must return true. If the listener neither calls suggest synchronously nor returns true, then suggest will be called automatically. The DownloadItem will not complete until all listeners have called suggest. Listeners may call suggest without any arguments in order to allow the download to use downloadItem.filename for its filename, or pass a suggestion object to suggest in order to override the target filename. If more than one extension overrides the filename, then the last extension installed whose listener passes a suggestion object to suggest wins. In order to avoid confusion regarding which extension will win, users should not install extensions that may conflict. If the download is initiated by download and the target filename is known before the MIME type and tentative filename have been determined, pass filename to download instead. */ export var onDeterminingFilename: DownloadDeterminingFilenameEvent; - } - //////////////////// - // Enterprise Platform Keys - //////////////////// - /** - * Use the `Browser.enterprise.platformKeys` API to generate keys and install certificates for these keys. The certificates will be managed by the platform and can be used for TLS authentication, network access or by other extension through {@link Browser.platformKeys}. - * - * Permissions: "enterprise.platformKeys" - * - * Note: Only available to policy installed extensions. - * @platform ChromeOS only + interface _DownloadOptionsHeaders { + /** Name of the HTTP header. */ + name: string; + /** Value of the HTTP header. */ + value: string; + } + + /** What to download and how. */ + interface _DownloadOptions { + /** The URL to download. */ + url: string; + /** A file path relative to the Downloads directory to contain the downloaded file. */ + filename?: string | undefined; + /** Whether to associate the download with a private browsing session. */ + incognito?: boolean | undefined; + /** The cookie store ID of the contextual identity; requires "cookies" permission. */ + cookieStoreId?: string | undefined; + conflictAction?: FilenameConflictAction | undefined; + /** + * Use a file-chooser to allow the user to select a filename. If the option is not specified, the file chooser will be shown only if the Firefox "Always ask you where to save files" option is enabled (i.e. the pref `browser.download.useDownloadDir` is set to `false`). + */ + saveAs?: boolean | undefined; + /** The HTTP method to use if the URL uses the HTTP[S] protocol. */ + method?: _DownloadOptionsMethod | undefined; + /** + * Extra HTTP headers to send with the request if the URL uses the HTTP[s] protocol. Each header is represented as a dictionary containing the keys `name` and either `value` or `binaryValue`, restricted to those allowed by XMLHttpRequest. + */ + headers?: _DownloadOptionsHeaders[] | undefined; + /** Post body. */ + body?: string | undefined; + /** + * When this flag is set to `true`, then the browser will allow downloads to proceed after encountering HTTP errors such as `404 Not Found`. + */ + allowHttpErrors?: boolean | undefined; + } + + interface _GetFileIconOptions { + /** + * The size of the icon. The returned icon will be square with dimensions size * size pixels. The default size for the icon is 32x32 pixels. + */ + size?: number | undefined; + } + + interface _OnChangedDownloadDelta { + /** The `id` of the DownloadItem that changed. */ + id: number; + /** Describes a change in a DownloadItem's `url`. */ + url?: StringDelta | undefined; + /** Describes a change in a DownloadItem's `filename`. */ + filename?: StringDelta | undefined; + /** Describes a change in a DownloadItem's `danger`. */ + danger?: StringDelta | undefined; + /** Describes a change in a DownloadItem's `mime`. */ + mime?: StringDelta | undefined; + /** Describes a change in a DownloadItem's `startTime`. */ + startTime?: StringDelta | undefined; + /** Describes a change in a DownloadItem's `endTime`. */ + endTime?: StringDelta | undefined; + /** Describes a change in a DownloadItem's `state`. */ + state?: StringDelta | undefined; + canResume?: BooleanDelta | undefined; + /** Describes a change in a DownloadItem's `paused`. */ + paused?: BooleanDelta | undefined; + /** Describes a change in a DownloadItem's `error`. */ + error?: StringDelta | undefined; + /** Describes a change in a DownloadItem's `totalBytes`. */ + totalBytes?: DoubleDelta | undefined; + /** Describes a change in a DownloadItem's `fileSize`. */ + fileSize?: DoubleDelta | undefined; + exists?: BooleanDelta | undefined; + } + + /** This event fires with the DownloadItem object when a download begins. */ + const onCreated: WebExtEvent<(downloadItem: DownloadItem) => void>; + /** + * Fires with the `downloadId` when a download is erased from history. + * @param downloadId The `id` of the DownloadItem that was erased. + */ + const onErased: WebExtEvent<(downloadId: number) => void>; + /** + * When any of a DownloadItem's properties except `bytesReceived` changes, this event fires with the `downloadId` and an object containing the properties that changed. + */ + const onChanged: WebExtEvent<(downloadDelta: _OnChangedDownloadDelta) => void>; + } + + /** + * Use the `chrome.enterprise.platformKeys` API to generate keys and install certificates for these keys. The certificates will be managed by the platform and can be used for TLS authentication, network access or by other extension through {@link chrome.platformKeys}. + * + * Permissions: "enterprise.platformKeys" + * + * Note: Only available to policy installed extensions. + * @platform ChromeOS only */ export namespace enterprise.platformKeys { export interface Token { @@ -4013,7 +4781,7 @@ export namespace Browser { */ export enum Algorithm { ECDSA = "ECDSA", - RSA = "RSA", + RSA = "RSA" } /** @@ -4022,7 +4790,7 @@ export namespace Browser { */ export enum Scope { USER = "USER", - MACHINE = "MACHINE", + MACHINE = "MACHINE" } /** @@ -4032,7 +4800,6 @@ export namespace Browser { */ export function getTokens(): Promise; export function getTokens(callback: (tokens: Token[]) => void): void; - /** * Returns the list of all client certificates available from the given token. Can be used to check for the existence and expiration of client certificates that are usable for a certain authentication. * @param tokenId The id of a Token returned by getTokens. @@ -4041,7 +4808,6 @@ export namespace Browser { */ export function getCertificates(tokenId: string): Promise; export function getCertificates(tokenId: string, callback: (certificates: ArrayBuffer[]) => void): void; - /** * Imports `certificate` to the given token if the certified key is already stored in this token. After a successful certification request, this function should be used to store the obtained certificate and to make it available to the operating system and browser for authentication. * @param tokenId The id of a Token returned by getTokens. @@ -4051,7 +4817,6 @@ export namespace Browser { */ export function importCertificate(tokenId: string, certificate: ArrayBuffer): Promise; export function importCertificate(tokenId: string, certificate: ArrayBuffer, callback: () => void): void; - /** * Removes `certificate` from the given token if present. Should be used to remove obsolete certificates so that they are not considered during authentication and do not clutter the certificate choice. Should be used to free storage in the certificate store. * @param tokenId The id of a Token returned by getTokens. @@ -4061,7 +4826,6 @@ export namespace Browser { */ export function removeCertificate(tokenId: string, certificate: ArrayBuffer): Promise; export function removeCertificate(tokenId: string, certificate: ArrayBuffer, callback: () => void): void; - /** * Similar to `challengeMachineKey` and `challengeUserKey`, but allows specifying the algorithm of a registered key. Challenges a hardware-backed Enterprise Machine Key and emits the response as part of a remote attestation protocol. Only useful on ChromeOS and in conjunction with the Verified Access Web API which both issues challenges and verifies responses. * @@ -4076,7 +4840,6 @@ export namespace Browser { */ export function challengeKey(options: ChallengeKeyOptions): Promise; export function challengeKey(options: ChallengeKeyOptions, callback: (response: ArrayBuffer) => void): void; - /** * @deprecated Deprecated since Chrome 110, use {@link challengeKey} instead. * @@ -4098,12 +4861,7 @@ export namespace Browser { export function challengeMachineKey(challenge: ArrayBuffer): Promise; export function challengeMachineKey(challenge: ArrayBuffer, registerKey: boolean): Promise; export function challengeMachineKey(challenge: ArrayBuffer, callback: (response: ArrayBuffer) => void): void; - export function challengeMachineKey( - challenge: ArrayBuffer, - registerKey: boolean, - callback: (response: ArrayBuffer) => void, - ): void; - + export function challengeMachineKey(challenge: ArrayBuffer, registerKey: boolean, callback: (response: ArrayBuffer) => void): void; /** * @deprecated Deprecated since Chrome 110, use {@link challengeKey} instead. * @@ -4122,18 +4880,11 @@ export namespace Browser { * @since Chrome 50 */ export function challengeUserKey(challenge: ArrayBuffer, registerKey: boolean): Promise; - export function challengeUserKey( - challenge: ArrayBuffer, - registerKey: boolean, - callback: (response: ArrayBuffer) => void, - ): void; + export function challengeUserKey(challenge: ArrayBuffer, registerKey: boolean, callback: (response: ArrayBuffer) => void): void; } - //////////////////// - // Enterprise Device Attributes - //////////////////// /** - * Use the `Browser.enterprise.deviceAttributes` API to read device attributes. + * Use the `chrome.enterprise.deviceAttributes` API to read device attributes. * * Permissions: "enterprise.deviceAttributes" * @@ -4184,11 +4935,8 @@ export namespace Browser { export function getDeviceHostname(callback: (hostname: string) => void): void; } - //////////////////// - // Enterprise Hardware Platform - //////////////////// /** - * Use the `Browser.enterprise.hardwarePlatform` API to get the manufacturer and model of the hardware platform where the browser runs. + * Use the `chrome.enterprise.hardwarePlatform` API to get the manufacturer and model of the hardware platform where the browser runs. * * Permissions: "enterprise.hardwarePlatform" * @@ -4209,11 +4957,8 @@ export namespace Browser { export function getHardwarePlatformInfo(callback: (info: HardwarePlatformInfo) => void): void; } - //////////////////// - // Enterprise Networking Attributes - //////////////////// /** - * Use the `Browser.enterprise.networkingAttributes` API to read information about your current network. Note: This API is only available to extensions force-installed by enterprise policy. + * Use the `chrome.enterprise.networkingAttributes` API to read information about your current network. Note: This API is only available to extensions force-installed by enterprise policy. * * Permissions: "enterprise.networkingAttributes" * @@ -4238,16 +4983,13 @@ export namespace Browser { export function getNetworkDetails(callback: (networkDetails: NetworkDetails) => void): void; } - //////////////////// - // Events - //////////////////// /** - * The `Browser.events` namespace contains common types used by APIs dispatching events to notify you when something interesting happens. + * The `chrome.events` namespace contains common types used by APIs dispatching events to notify you when something interesting happens. */ export namespace events { /** Filters URLs for various criteria. See event filtering. All criteria are case sensitive. */ export interface UrlFilter { - /** Optional. Matches if the scheme of the URL is equal to any of the schemes specified in the array. */ + /** Optional. Matches if the scheme of the URL is equal to any of the schemes specified in the array. */ schemes?: string[] | undefined; /** * Optional. @@ -4255,39 +4997,39 @@ export namespace Browser { * Matches if the URL (without fragment identifier) matches a specified regular expression. Port numbers are stripped from the URL if they match the default port number. The regular expressions use the RE2 syntax. */ urlMatches?: string | undefined; - /** Optional. Matches if the path segment of the URL contains a specified string. */ + /** Optional. Matches if the path segment of the URL contains a specified string. */ pathContains?: string | undefined; - /** Optional. Matches if the host name of the URL ends with a specified string. */ + /** Optional. Matches if the host name of the URL ends with a specified string. */ hostSuffix?: string | undefined; - /** Optional. Matches if the host name of the URL starts with a specified string. */ + /** Optional. Matches if the host name of the URL starts with a specified string. */ hostPrefix?: string | undefined; - /** Optional. Matches if the host name of the URL contains a specified string. To test whether a host name component has a prefix 'foo', use hostContains: '.foo'. This matches 'www.foobar.com' and 'foo.com', because an implicit dot is added at the beginning of the host name. Similarly, hostContains can be used to match against component suffix ('foo.') and to exactly match against components ('.foo.'). Suffix- and exact-matching for the last components need to be done separately using hostSuffix, because no implicit dot is added at the end of the host name. */ + /** Optional. Matches if the host name of the URL contains a specified string. To test whether a host name component has a prefix 'foo', use hostContains: '.foo'. This matches 'www.foobar.com' and 'foo.com', because an implicit dot is added at the beginning of the host name. Similarly, hostContains can be used to match against component suffix ('foo.') and to exactly match against components ('.foo.'). Suffix- and exact-matching for the last components need to be done separately using hostSuffix, because no implicit dot is added at the end of the host name. */ hostContains?: string | undefined; - /** Optional. Matches if the URL (without fragment identifier) contains a specified string. Port numbers are stripped from the URL if they match the default port number. */ + /** Optional. Matches if the URL (without fragment identifier) contains a specified string. Port numbers are stripped from the URL if they match the default port number. */ urlContains?: string | undefined; - /** Optional. Matches if the query segment of the URL ends with a specified string. */ + /** Optional. Matches if the query segment of the URL ends with a specified string. */ querySuffix?: string | undefined; - /** Optional. Matches if the URL (without fragment identifier) starts with a specified string. Port numbers are stripped from the URL if they match the default port number. */ + /** Optional. Matches if the URL (without fragment identifier) starts with a specified string. Port numbers are stripped from the URL if they match the default port number. */ urlPrefix?: string | undefined; - /** Optional. Matches if the host name of the URL is equal to a specified string. */ + /** Optional. Matches if the host name of the URL is equal to a specified string. */ hostEquals?: string | undefined; - /** Optional. Matches if the URL (without fragment identifier) is equal to a specified string. Port numbers are stripped from the URL if they match the default port number. */ + /** Optional. Matches if the URL (without fragment identifier) is equal to a specified string. Port numbers are stripped from the URL if they match the default port number. */ urlEquals?: string | undefined; - /** Optional. Matches if the query segment of the URL contains a specified string. */ + /** Optional. Matches if the query segment of the URL contains a specified string. */ queryContains?: string | undefined; - /** Optional. Matches if the path segment of the URL starts with a specified string. */ + /** Optional. Matches if the path segment of the URL starts with a specified string. */ pathPrefix?: string | undefined; - /** Optional. Matches if the path segment of the URL is equal to a specified string. */ + /** Optional. Matches if the path segment of the URL is equal to a specified string. */ pathEquals?: string | undefined; - /** Optional. Matches if the path segment of the URL ends with a specified string. */ + /** Optional. Matches if the path segment of the URL ends with a specified string. */ pathSuffix?: string | undefined; - /** Optional. Matches if the query segment of the URL is equal to a specified string. */ + /** Optional. Matches if the query segment of the URL is equal to a specified string. */ queryEquals?: string | undefined; - /** Optional. Matches if the query segment of the URL starts with a specified string. */ + /** Optional. Matches if the query segment of the URL starts with a specified string. */ queryPrefix?: string | undefined; - /** Optional. Matches if the URL (without fragment identifier) ends with a specified string. Port numbers are stripped from the URL if they match the default port number. */ + /** Optional. Matches if the URL (without fragment identifier) ends with a specified string. Port numbers are stripped from the URL if they match the default port number. */ urlSuffix?: string | undefined; - /** Optional. Matches if the port of the URL is contained in any of the specified port lists. For example [80, 443, [1000, 1200]] matches all requests on port 80, 443 and in the range 1000-1200. */ + /** Optional. Matches if the port of the URL is contained in any of the specified port lists. For example [80, 443, [1000, 1200]] matches all requests on port 80, 443 and in the range 1000-1200. */ ports?: Array | undefined; /** * Optional. @@ -4307,27 +5049,20 @@ export namespace Browser { * Returns currently registered rules. * @param callback Called with registered rules. */ - getRules( - callback: ( + getRules(callback: ( /** Rules that were registered, the optional parameters are filled with values */ rules: Rule[], - ) => void, - ): void; + ) => void): void; /** * Returns currently registered rules. * @param ruleIdentifiers If an array is passed, only rules with identifiers contained in this array are returned. * @param callback Called with registered rules. */ - getRules( - ruleIdentifiers: string[], - callback: ( + getRules(ruleIdentifiers: string[], callback: ( /** Rules that were registered, the optional parameters are filled with values */ rules: Rule[], - ) => void, - ): void; - /** - * @param callback Listener whose registration status shall be tested. - */ + ) => void): void; + /** @param callback Listener whose registration status shall be tested. */ hasListener(callback: T): boolean; /** * Unregisters currently registered rules. @@ -4345,13 +5080,10 @@ export namespace Browser { * @param rules Rules to be registered. These do not replace previously registered rules. * @param callback Called with registered rules. */ - addRules( - rules: Rule[], - callback?: ( + addRules(rules: Rule[], callback?: ( /** Rules that were registered, the optional parameters are filled with values */ rules: Rule[], - ) => void, - ): void; + ) => void): void; /** * Deregisters an event listener callback from an event. * @param callback Listener that shall be unregistered. @@ -4362,11 +5094,11 @@ export namespace Browser { /** Description of a declarative rule for handling events. */ export interface Rule { - /** Optional. Optional priority of this rule. Defaults to 100. */ + /** Optional. Optional priority of this rule. Defaults to 100. */ priority?: number | undefined; /** List of conditions that can trigger the actions. */ conditions: any[]; - /** Optional. Optional identifier that allows referencing this rule. */ + /** Optional. Optional identifier that allows referencing this rule. */ id?: string | undefined; /** List of actions that are triggered if one of the condtions is fulfilled. */ actions: any[]; @@ -4379,11 +5111,8 @@ export namespace Browser { } } - //////////////////// - // Extension - //////////////////// /** - * 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. + * The `chrome.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 { export interface FetchProperties { @@ -4393,9 +5122,9 @@ export namespace Browser { * Find a view according to a tab id. If this field is omitted, returns all views. */ tabId?: number | undefined; - /** Optional. The window to restrict the search to. If omitted, returns all views. */ + /** Optional. 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'. */ + /** 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; } @@ -4404,12 +5133,11 @@ export namespace Browser { 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) - > - {} + export interface OnRequestEvent extends chrome.events.Event< + | ((request: any, sender: runtime.MessageSender, sendResponse: (response: any) => void) => void) + | ((sender: runtime.MessageSender, sendResponse: (response: any) => void) => void) + > { + } /** * @since Chrome 7 @@ -4418,7 +5146,6 @@ export namespace Browser { 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; - /** 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; /** @@ -4465,11 +5192,7 @@ export namespace Browser { * 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( - extensionId: string, - request: Request, - responseCallback?: (response: Response) => void, - ): void; + export function sendRequest(extensionId: string, request: Request, responseCallback?: (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. @@ -4477,16 +5200,12 @@ export namespace Browser { * 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, - ): void; + export function sendRequest(request: Request, responseCallback?: (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"}. */ 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. @@ -4497,13 +5216,148 @@ export namespace Browser { * @deprecated Deprecated since Chrome 33. Please use runtime.onMessageExternal. */ export var onRequestExternal: OnRequestEvent; + + /** + * Set for the lifetime of a callback if an ansychronous extension api has resulted in an error. If no error has occured lastError will be `undefined`. + * @deprecated Please use `runtime.lastError`. + * Not supported on manifest versions above 2. + */ + interface _LastError { + /** Description of the error that has taken place. */ + message: string; + } + + interface _GetViewsFetchProperties { + /** + * The type of view to get. If omitted, returns all views (including background pages and tabs). Valid values: 'tab', 'popup', 'sidebar'. + */ + type?: ViewType | undefined; + /** The window to restrict the search to. If omitted, returns all views. */ + windowId?: number | undefined; + /** Find a view according to a tab id. If this field is omitted, returns all views. */ + tabId?: number | undefined; + } + + /** + * Set for the lifetime of a callback if an ansychronous extension api has resulted in an error. If no error has occured lastError will be `undefined`. + * @deprecated Please use `runtime.lastError`. + * Not supported on manifest versions above 2. + */ + const lastError: _LastError | undefined; + /** + * True for content scripts running inside incognito tabs, and for extension pages running inside an incognito process. The latter only applies to extensions with 'split' incognito_behavior. + */ + const inIncognitoContext: boolean | undefined; + /** + * Fired when a request is sent from either an extension process or a content script. + * @param request The request sent by the calling script. + * @param sendResponse Function to call (at most once) when you have a response. The argument should be any JSON-ifiable object, or undefined if there is no response. If you have more than one `onRequest` listener in the same document, then only one may send a response. + * @deprecated Please use `runtime.onMessage`. + */ + const onRequest: | WebExtEvent<(request: any, sender: runtime.MessageSender, sendResponse: (response?: any) => void) => void> + | undefined; + /** + * Fired when a request is sent from another extension. + * @param request The request sent by the calling script. + * @param sendResponse Function to call when you have a response. The argument should be any JSON-ifiable object, or undefined if there is no response. + * @deprecated Please use `runtime.onMessageExternal`. + */ + const onRequestExternal: | WebExtEvent<(request: any, sender: runtime.MessageSender, sendResponse: (response?: any) => void) => void> + | undefined; + } + + /** The `chrome.extensionTypes` API contains type declarations for Chrome extensions. */ + export namespace extensionTypes { + /** + * The origin of injected CSS. + * @since Chrome 66 + */ + export type CSSOrigin = "author" | "user"; + /** + * The document lifecycle of the frame. + * @since Chrome 106 + */ + export type DocumentLifecycle = "prerender" | "active" | "cached" | "pending_deletion"; + /** + * The type of frame. + * @since Chrome 106 + */ + export type FrameType = "outermost_frame" | "fenced_frame" | "sub_frame"; + + /** Details about the format and quality of an image. */ + export interface ImageDetails { + /** The format of the resulting image. Default is `"jpeg"`. */ + format?: ImageFormat | undefined; + /** When format is `"jpeg"`, controls the quality of the resulting image. This value is ignored for PNG images. As quality is decreased, the resulting image will have more visual artifacts, and the number of bytes needed to store it will decrease. */ + quality?: number | undefined; + } + + /** + * The format of an image. + * @since Chrome 44 + */ + export type ImageFormat = "jpeg" | "png"; + + /** Details of the script or CSS to inject. Either the code or the file property must be set, but both may not be set at the same time. */ + export interface InjectDetails { + /** If allFrames is `true`, implies that the JavaScript or CSS should be injected into all frames of current page. By default, it's `false` and is only injected into the top frame. If `true` and `frameId` is set, then the code is inserted in the selected frame and all of its child frames. */ + allFrames?: boolean | undefined; + /** + * JavaScript or CSS code to inject. + * + * **Warning:** Be careful using the `code` parameter. Incorrect use of it may open your extension to cross site scripting attacks + */ + code?: string | undefined; + /** + * The origin of the CSS to inject. This may only be specified for CSS, not JavaScript. Defaults to `"author"`. + * @since Chrome 66 + */ + cssOrigin?: CSSOrigin | undefined; + /** JavaScript or CSS file to inject. */ + file?: string | undefined; + /** + * The frame where the script or CSS should be injected. Defaults to 0 (the top-level frame). + * @since Chrome 50 + */ + frameId?: number | undefined; + /** If matchAboutBlank is true, then the code is also injected in about:blank and about:srcdoc frames if your extension has access to its parent document. Code cannot be inserted in top-level about:-frames. By default it is `false`. */ + matchAboutBlank?: boolean; + /** The soonest that the JavaScript or CSS will be injected into the tab. Defaults to "document_idle". */ + runAt?: RunAt | undefined; + } + + /** + * The soonest that the JavaScript or CSS will be injected into the tab. + * + * "document_start" : Script is injected after any files from css, but before any other DOM is constructed or any other script is run. + * + * "document_end" : Script is injected immediately after the DOM is complete, but before subresources like images and frames have loaded. + * + * "document_idle" : The browser chooses a time to inject the script between "document_end" and immediately after the `window.onload` event fires. The exact moment of injection depends on how complex the document is and how long it is taking to load, and is optimized for page load speed. Content scripts running at "document_idle" don't need to listen for the `window.onload` event; they are guaranteed to run after the DOM completes. If a script definitely needs to run after `window.onload`, the extension can check if `onload` has already fired by using the `document.readyState` property. + * @since Chrome 44 + */ + export type RunAt = "document_start" | "document_end" | "document_idle"; + + /** + * The area of the document to capture, in CSS pixels, relative to the page. If omitted, capture the visible viewport. + */ + interface _ImageDetailsRect { + x: number; + y: number; + width: number; + height: number; + } + + interface _PlainJSONArray extends Array { + } + + interface _PlainJSONObject { + [key: string]: PlainJSONValue; + } } - //////////////////// - // File Browser Handler - //////////////////// /** - * Use the `Browser.fileBrowserHandler` API to extend the Chrome OS file browser. For example, you can use this API to enable users to upload files to your website. + * Use the `chrome.fileBrowserHandler` API to extend the Chrome OS file browser. For example, you can use this API to enable users to upload files to your website. * * Permissions: "fileBrowserHandler" * @platform ChromeOS only @@ -4521,7 +5375,7 @@ export namespace Browser { } export interface SelectionResult { - /** Optional. Selected file entry. It will be null if a file hasn't been selected. */ + /** 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; @@ -4529,15 +5383,14 @@ export namespace Browser { /** 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. */ + /** Optional. The ID of the tab that raised this event. Tab IDs are unique within a browser session. */ tab_id?: number | undefined; /** 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> - {} + export interface FileBrowserHandlerExecuteEvent extends chrome.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. @@ -4547,16 +5400,12 @@ export namespace Browser { * 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; } - //////////////////// - // File System Provider - //////////////////// /** - * Use the `Browser.fileSystemProvider` API to create file systems, that can be accessible from the file manager on Chrome OS. + * Use the `chrome.fileSystemProvider` API to create file systems, that can be accessible from the file manager on Chrome OS. * * Permissions: "fileSystemProvider" * @platform ChromeOS only @@ -4605,7 +5454,7 @@ export namespace Browser { /** Type of a change detected on the observed directory. */ export enum ChangeType { CHANGED = "CHANGED", - DELETED = "DELETED", + DELETED = "DELETED" } export interface CloseFileRequestedOptions { @@ -4638,7 +5487,7 @@ export namespace Browser { export enum CommonActionId { SAVE_FOR_OFFLINE = "SAVE_FOR_OFFLINE", OFFLINE_NOT_NECESSARY = "OFFLINE_NOT_NECESSARY", - SHARE = "SHARE", + SHARE = "SHARE" } /** @since Chrome 44 */ @@ -4872,7 +5721,7 @@ export namespace Browser { /** Mode of opening a file. Used by {@link onOpenFileRequested}. */ export enum OpenFileMode { READ = "READ", - WRITE = "WRITE", + WRITE = "WRITE" } export interface OpenFileRequestedOptions { @@ -4886,7 +5735,7 @@ export namespace Browser { requestId: number; } - /** Error codes used by providing extensions in response to requests as well as in case of errors when calling methods of the API. For success, `"OK"` must be used.*/ + /** Error codes used by providing extensions in response to requests as well as in case of errors when calling methods of the API. For success, `"OK"` must be used. */ export enum ProviderError { OK = "OK", FAILED = "FAILED", @@ -4904,7 +5753,7 @@ export namespace Browser { NOT_A_FILE = "NOT_A_FILE", NOT_EMPTY = "NOT_EMPTY", INVALID_URL = "INVALID_URL", - IO = "IO", + IO = "IO" } export interface ReadDirectoryRequestedOptions { @@ -5022,7 +5871,6 @@ export namespace Browser { */ export function get(fileSystemId: string): Promise; export function get(fileSystemId: string, callback: (fileSystem: FileSystemInfo) => void): void; - /** * Returns all file systems mounted by the extension. * @@ -5030,7 +5878,6 @@ export namespace Browser { */ export function getAll(): Promise; export function getAll(callback: (fileSystems: FileSystemInfo[]) => void): void; - /** * Mounts a file system with the given `fileSystemId` and `displayName`. `displayName` will be shown in the left panel of the Files app. `displayName` can contain any characters including '/', but cannot be an empty string. `displayName` must be descriptive but doesn't have to be unique. The `fileSystemId` must not be an empty string. * @@ -5042,7 +5889,6 @@ export namespace Browser { */ export function mount(options: MountOptions): Promise; export function mount(options: MountOptions, callback: () => void): void; - /** * Notifies about changes in the watched directory at `observedPath` in `recursive` mode. If the file system is mounted with `supportsNotifyTag`, then `tag` must be provided, and all changes since the last notification always reported, even if the system was shutdown. The last tag can be obtained with {@link getAll}. * @@ -5061,7 +5907,6 @@ export namespace Browser { */ export function notify(options: NotifyOptions): Promise; export function notify(options: NotifyOptions, callback: () => void): void; - /** * Unmounts a file system with the given `fileSystemId`. It must be called after {@link onUnmountRequested} is invoked. Also, the providing extension can decide to perform unmounting if not requested (eg. in case of lost connection, or a file error). * @@ -5071,255 +5916,232 @@ export namespace Browser { */ export function unmount(options: UnmountOptions): Promise; export function unmount(options: UnmountOptions, callback: () => void): void; - /** Raised when aborting an operation with `operationRequestId` is requested. The operation executed with `operationRequestId` must be immediately stopped and `successCallback` of this abort request executed. If aborting fails, then `errorCallback` must be called. Note, that callbacks of the aborted operation must not be called, as they will be ignored. Despite calling `errorCallback`, the request may be forcibly aborted. */ export const onAbortRequested: events.Event< - ( - options: AbortRequestedOptions, - successCallback: () => void, - errorCallback: (error: `${ProviderError}`) => void, - ) => void - >; - + ( + options: AbortRequestedOptions, + successCallback: () => void, + errorCallback: (error: `${ProviderError}`) => void, + ) => void + >; /** * Raised when setting a new directory watcher is requested. If an error occurs, then `errorCallback` must be called. * @since Chrome 45 */ export const onAddWatcherRequested: events.Event< - ( - options: AddWatcherRequestedOptions, - successCallback: () => void, - errorCallback: (error: `${ProviderError}`) => void, - ) => void - >; - - /** Raised when opening a file previously opened with `openRequestId` is requested to be closed.*/ + ( + options: AddWatcherRequestedOptions, + successCallback: () => void, + errorCallback: (error: `${ProviderError}`) => void, + ) => void + >; + /** Raised when opening a file previously opened with `openRequestId` is requested to be closed. */ export const onCloseFileRequested: events.Event< - ( - options: CloseFileRequestedOptions, - successCallback: () => void, - errorCallback: (error: `${ProviderError}`) => void, - ) => void - >; - + ( + options: CloseFileRequestedOptions, + successCallback: () => void, + errorCallback: (error: `${ProviderError}`) => void, + ) => void + >; /** * Raised when showing a configuration dialog for `fileSystemId` is requested. If it's handled, the `file_system_provider.configurable` manifest option must be set to true. * @since Chrome 44 */ export const onConfigureRequested: events.Event< - ( - options: ConfigureRequestedOptions, - successCallback: () => void, - errorCallback: (error: `${ProviderError}`) => void, - ) => void - >; - + ( + options: ConfigureRequestedOptions, + successCallback: () => void, + errorCallback: (error: `${ProviderError}`) => void, + ) => void + >; /** Raised when copying an entry (recursively if a directory) is requested. If an error occurs, then `errorCallback` must be called. */ export const onCopyEntryRequested: events.Event< - ( - options: CopyEntryRequestedOptions, - successCallback: () => void, - errorCallback: (error: `${ProviderError}`) => void, - ) => void - >; - + ( + options: CopyEntryRequestedOptions, + successCallback: () => void, + errorCallback: (error: `${ProviderError}`) => void, + ) => void + >; /** Raised when creating a directory is requested. The operation must fail with the EXISTS error if the target directory already exists. If `recursive` is true, then all of the missing directories on the directory path must be created. */ export const onCreateDirectoryRequested: events.Event< - ( - options: CreateDirectoryRequestedOptions, - successCallback: () => void, - errorCallback: ( - error: `${ProviderError}`, - ) => void, - ) => void - >; - + ( + options: CreateDirectoryRequestedOptions, + successCallback: () => void, + errorCallback: ( + error: `${ProviderError}`, + ) => void, + ) => void + >; /** Raised when creating a file is requested. If the file already exists, then `errorCallback` must be called with the `"EXISTS"` error code. */ export const onCreateFileRequested: events.Event< - ( - options: CreateFileRequestedOptions, - successCallback: () => void, - errorCallback: ( - error: `${ProviderError}`, - ) => void, - ) => void - >; - + ( + options: CreateFileRequestedOptions, + successCallback: () => void, + errorCallback: ( + error: `${ProviderError}`, + ) => void, + ) => void + >; /** Raised when deleting an entry is requested. If `recursive` is true, and the entry is a directory, then all of the entries inside must be recursively deleted as well. */ export const onDeleteEntryRequested: events.Event< - ( - options: DeleteEntryRequestedOptions, - successCallback: () => void, - errorCallback: ( - error: `${ProviderError}`, - ) => void, - ) => void - >; - + ( + options: DeleteEntryRequestedOptions, + successCallback: () => void, + errorCallback: ( + error: `${ProviderError}`, + ) => void, + ) => void + >; /** * Raised when executing an action for a set of files or directories is\\ requested. After the action is completed, `successCallback` must be called. On error, `errorCallback` must be called. * @since Chrome 48 */ export const onExecuteActionRequested: events.Event< - ( - options: ExecuteActionRequestedOptions, - successCallback: () => void, - errorCallback: ( - error: `${ProviderError}`, - ) => void, - ) => void - >; - + ( + options: ExecuteActionRequestedOptions, + successCallback: () => void, + errorCallback: ( + error: `${ProviderError}`, + ) => void, + ) => void + >; /** * Raised when a list of actions for a set of files or directories at `entryPaths` is requested. All of the returned actions must be applicable to each entry. If there are no such actions, an empty array should be returned. The actions must be returned with the `successCallback` call. In case of an error, `errorCallback` must be called. * @since Chrome 48 */ export const onGetActionsRequested: events.Event< - ( - options: GetActionsRequestedOptions, - successCallback: ( - actions: Action[], - ) => void, - errorCallback: ( - error: `${ProviderError}`, - ) => void, - ) => void - >; - + ( + options: GetActionsRequestedOptions, + successCallback: ( + actions: Action[], + ) => void, + errorCallback: ( + error: `${ProviderError}`, + ) => void, + ) => void + >; /** Raised when metadata of a file or a directory at `entryPath` is requested. The metadata must be returned with the `successCallback` call. In case of an error, `errorCallback` must be called. */ export const onGetMetadataRequested: events.Event< - ( - options: GetMetadataRequestedOptions, - successCallback: ( - metadata: EntryMetadata, - ) => void, - errorCallback: ( - error: `${ProviderError}`, - ) => void, - ) => void - >; - + ( + options: GetMetadataRequestedOptions, + successCallback: ( + metadata: EntryMetadata, + ) => void, + errorCallback: ( + error: `${ProviderError}`, + ) => void, + ) => void + >; /** * Raised when showing a dialog for mounting a new file system is requested. If the extension/app is a file handler, then this event shouldn't be handled. Instead `app.runtime.onLaunched` should be handled in order to mount new file systems when a file is opened. For multiple mounts, the `file_system_provider.multiple_mounts` manifest option must be set to true. * @since Chrome 44 */ export const onMountRequested: events.Event< - ( - successCallback: () => void, - errorCallback: ( - error: `${ProviderError}`, - ) => void, - ) => void - >; - + ( + successCallback: () => void, + errorCallback: ( + error: `${ProviderError}`, + ) => void, + ) => void + >; /** Raised when moving an entry (recursively if a directory) is requested. If an error occurs, then `errorCallback` must be called. */ export const onMoveEntryRequested: events.Event< - ( - options: MoveEntryRequestedOptions, - successCallback: () => void, - errorCallback: ( - error: `${ProviderError}`, - ) => void, - ) => void - >; - + ( + options: MoveEntryRequestedOptions, + successCallback: () => void, + errorCallback: ( + error: `${ProviderError}`, + ) => void, + ) => void + >; /** Raised when opening a file at `filePath` is requested. If the file does not exist, then the operation must fail. Maximum number of files opened at once can be specified with `MountOptions`. */ export const onOpenFileRequested: events.Event< - ( - options: OpenFileRequestedOptions, - successCallback: ( - /** - * @since Chrome 125 - */ - metadata?: EntryMetadata, - ) => void, - errorCallback: ( - error: `${ProviderError}`, - ) => void, - ) => void - >; - + ( + options: OpenFileRequestedOptions, + successCallback: ( + /** + * @since Chrome 125 + */ + metadata?: EntryMetadata, + ) => void, + errorCallback: ( + error: `${ProviderError}`, + ) => void, + ) => void + >; /** Raised when contents of a directory at `directoryPath` are requested. The results must be returned in chunks by calling the `successCallback` several times. In case of an error, `errorCallback` must be called. */ export const onReadDirectoryRequested: events.Event< - ( - options: ReadDirectoryRequestedOptions, - successCallback: ( - entries: EntryMetadata[], - hasMore: boolean, - ) => void, - errorCallback: ( - error: `${ProviderError}`, - ) => void, - ) => void - >; - + ( + options: ReadDirectoryRequestedOptions, + successCallback: ( + entries: EntryMetadata[], + hasMore: boolean, + ) => void, + errorCallback: ( + error: `${ProviderError}`, + ) => void, + ) => void + >; /** Raised when reading contents of a file opened previously with `openRequestId` is requested. The results must be returned in chunks by calling `successCallback` several times. In case of an error, `errorCallback` must be called. */ export const onReadFileRequested: events.Event< - ( - options: ReadFileRequestedOptions, - successCallback: ( - data: ArrayBuffer, - hasMore: boolean, - ) => void, - errorCallback: ( - error: `${ProviderError}`, - ) => void, - ) => void - >; - + ( + options: ReadFileRequestedOptions, + successCallback: ( + data: ArrayBuffer, + hasMore: boolean, + ) => void, + errorCallback: ( + error: `${ProviderError}`, + ) => void, + ) => void + >; /** * Raised when the watcher should be removed. If an error occurs, then `errorCallback` must be called. * @since Chrome 45 */ export const onRemoveWatcherRequested: events.Event< - ( - options: RemoveWatcherRequestedOptions, - successCallback: () => void, - errorCallback: ( - error: `${ProviderError}`, - ) => void, - ) => void - >; - + ( + options: RemoveWatcherRequestedOptions, + successCallback: () => void, + errorCallback: ( + error: `${ProviderError}`, + ) => void, + ) => void + >; /** Raised when truncating a file to a desired length is requested. If an error occurs, then `errorCallback` must be called. */ export const onTruncateRequested: events.Event< - ( - options: TruncateRequestedOptions, - successCallback: () => void, - errorCallback: ( - error: `${ProviderError}`, - ) => void, - ) => void - >; - + ( + options: TruncateRequestedOptions, + successCallback: () => void, + errorCallback: ( + error: `${ProviderError}`, + ) => void, + ) => void + >; /** Raised when unmounting for the file system with the `fileSystemId` identifier is requested. In the response, the {@link unmount} API method must be called together with `successCallback`. If unmounting is not possible (eg. due to a pending operation), then `errorCallback` must be called. */ export const onUnmountRequested: events.Event< - ( - options: UnmountRequestedOptions, - successCallback: () => void, - errorCallback: ( - error: `${ProviderError}`, - ) => void, - ) => void - >; - + ( + options: UnmountRequestedOptions, + successCallback: () => void, + errorCallback: ( + error: `${ProviderError}`, + ) => void, + ) => void + >; /** Raised when writing contents to a file opened previously with `openRequestId` is requested. */ export const onWriteFileRequested: events.Event< - ( - options: WriteFileRequestedOptions, - successCallback: () => void, - errorCallback: ( - error: `${ProviderError}`, - ) => void, - ) => void - >; + ( + options: WriteFileRequestedOptions, + successCallback: () => void, + errorCallback: ( + error: `${ProviderError}`, + ) => void, + ) => void + >; } - //////////////////// - // Font Settings - //////////////////// /** - * Use the `Browser.fontSettings` API to manage Chrome's font settings. + * Use the `chrome.fontSettings` API to manage Chrome's font settings. * * Permissions: "fontSettings" */ @@ -5339,14 +6161,13 @@ export namespace Browser { export interface FontDetails { /** The generic font family for the font. */ - genericFamily: - | "cursive" + genericFamily: | "cursive" | "fantasy" | "fixed" | "sansserif" | "serif" | "standard"; - /** Optional. The script for the font. If omitted, the global script font setting is affected. */ + /** Optional. The script for the font. If omitted, the global script font setting is affected. */ script?: string | undefined; } @@ -5355,7 +6176,7 @@ export namespace Browser { 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. */ + /** Optional. The script code for which the font setting has changed. */ script?: string | undefined; /** The font ID. See the description in getFont. */ fontId: string; @@ -5385,15 +6206,17 @@ export namespace Browser { fontId: string; } - export interface DefaultFixedFontSizeChangedEvent - extends Browser.events.Event<(details: FontSizeDetails) => void> - {} + export interface DefaultFixedFontSizeChangedEvent extends chrome.events.Event<(details: FontSizeDetails) => void> { + } - export interface DefaultFontSizeChangedEvent extends Browser.events.Event<(details: FontSizeDetails) => void> {} + export interface DefaultFontSizeChangedEvent extends chrome.events.Event<(details: FontSizeDetails) => void> { + } - export interface MinimumFontSizeChangedEvent extends Browser.events.Event<(details: FontSizeDetails) => void> {} + export interface MinimumFontSizeChangedEvent extends chrome.events.Event<(details: FontSizeDetails) => void> { + } - export interface FontChangedEvent extends Browser.events.Event<(details: FullFontDetails) => void> {} + export interface FontChangedEvent extends chrome.events.Event<(details: FullFontDetails) => void> { + } /** * Sets the default font size. @@ -5529,7 +6352,6 @@ export namespace Browser { * @param details This parameter is currently unused. */ export function clearDefaultFixedFontSize(details: unknown, callback: () => void): void; - /** Fired when the default fixed font size setting changes. */ export var onDefaultFixedFontSizeChanged: DefaultFixedFontSizeChangedEvent; /** Fired when the default font size setting changes. */ @@ -5540,11 +6362,8 @@ export namespace Browser { export var onFontChanged: FontChangedEvent; } - //////////////////// - // Google Cloud Messaging - //////////////////// /** - * Use `Browser.gcm` to enable apps and extensions to send and receive messages through Firebase Cloud Messaging (FCM). + * Use `chrome.gcm` to enable apps and extensions to send and receive messages through Firebase Cloud Messaging (FCM). * * Permissions: "gcm" */ @@ -5585,15 +6404,17 @@ export namespace Browser { detail: object; } - export interface MessageReceptionEvent extends Browser.events.Event<(message: IncomingMessage) => void> {} + export interface MessageReceptionEvent extends chrome.events.Event<(message: IncomingMessage) => void> { + } - export interface MessageDeletionEvent extends Browser.events.Event<() => void> {} + export interface MessageDeletionEvent extends chrome.events.Event<() => void> { + } - export interface GcmErrorEvent extends Browser.events.Event<(error: GcmError) => void> {} + export interface GcmErrorEvent extends chrome.events.Event<(error: GcmError) => void> { + } /** The maximum size (in bytes) of all key/value pairs in a message. */ export var MAX_MESSAGE_SIZE: number; - /** * Registers the application with GCM. The registration ID will be returned by the callback. If register is called again with the same list of senderIds, the same registration ID will be returned. * @param senderIds A list of server IDs that are allowed to send messages to the application. It should contain at least one and no more than 100 sender IDs. @@ -5613,7 +6434,6 @@ export namespace Browser { * Parameter messageId: The ID of the message that the callback was issued for. */ export function send(message: OutgoingMessage, callback: (messageId: string) => void): void; - /** Fired when a message is received through GCM. */ export var onMessage: MessageReceptionEvent; /** Fired when a GCM server had to delete messages sent by an app server to the application. See Messages deleted event section of Cloud Messaging documentation for details on handling this event. */ @@ -5622,11 +6442,8 @@ export namespace Browser { export var onSendError: GcmErrorEvent; } - //////////////////// - // History - //////////////////// /** - * Use the `Browser.history` API to interact with the browser's record of visited pages. You can add, remove, and query for URLs in the browser's history. To override the history page with your own version, see Override Pages. + * Use the `chrome.history` API to interact with the browser's record of visited pages. You can add, remove, and query for URLs in the browser's history. To override the history page with your own version, see Override Pages. * * Permissions: "history" */ @@ -5691,9 +6508,11 @@ export namespace Browser { urls?: string[] | undefined; } - export interface HistoryVisitedEvent extends Browser.events.Event<(result: HistoryItem) => void> {} + export interface HistoryVisitedEvent extends chrome.events.Event<(result: HistoryItem) => void> { + } - export interface HistoryVisitRemovedEvent extends Browser.events.Event<(removed: RemovedResult) => void> {} + export interface HistoryVisitRemovedEvent extends chrome.events.Event<(removed: RemovedResult) => void> { + } /** * Searches the history for the last visit time of each page matching the query. @@ -5749,29 +6568,93 @@ export namespace Browser { * 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; + + interface _SearchQuery { + /** A free-text query to the history service. Leave empty to retrieve all pages. */ + text: string; + /** + * Limit results to those visited after this date. If not specified, this defaults to 24 hours in the past. + */ + startTime?: extensionTypes.Date | undefined; + /** Limit results to those visited before this date. */ + endTime?: extensionTypes.Date | undefined; + /** The maximum number of results to retrieve. Defaults to 100. */ + maxResults?: number | undefined; + } + + interface _GetVisitsDetails { + /** + * The URL for which to retrieve visit information. It must be in the format as returned from a call to history.search. + */ + url: string; + } + + interface _AddUrlDetails { + /** The URL to add. Must be a valid URL that can be added to history. */ + url: string; + /** The title of the page. */ + title?: string | undefined; + /** The transition type for this visit from its referrer. */ + transition?: TransitionType | undefined; + /** The date when this visit occurred. */ + visitTime?: extensionTypes.Date | undefined; + } + + interface _DeleteUrlDetails { + /** The URL to remove. */ + url: string; + } + + interface _DeleteRangeRange { + /** Items added to history after this date. */ + startTime: extensionTypes.Date; + /** Items added to history before this date. */ + endTime: extensionTypes.Date; + } + + interface _OnVisitRemovedRemoved { + /** True if all history was removed. If true, then urls will be empty. */ + allHistory: boolean; + urls: string[]; + } + + interface _OnTitleChangedChanged { + /** The URL for which the title has changed */ + url: string; + /** The new title for the URL. */ + title: string; + } + + /** + * Fired when a URL is visited, providing the HistoryItem data for that URL. This event fires before the page has loaded. + */ + const onVisited: WebExtEvent<(result: HistoryItem) => void>; + /** + * Fired when one or more URLs are removed from the history service. When all visits have been removed the URL is purged from history. + */ + const onVisitRemoved: WebExtEvent<(removed: _OnVisitRemovedRemoved) => void>; + /** Fired when the title of a URL is changed in the browser history. */ + const onTitleChanged: WebExtEvent<(changed: _OnTitleChangedChanged) => void>; } - //////////////////// - // i18n - //////////////////// /** - * Use the `Browser.i18n` infrastructure to implement internationalization across your whole app or extension. + * Use the `chrome.i18n` infrastructure to implement internationalization across your whole app or extension. * * 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'. + /** + * 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 */ + * 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; } @@ -5780,7 +6663,6 @@ export namespace Browser { export interface LanguageDetectionResult { /** CLD detected language reliability */ isReliable: boolean; - /** Array of detectedLanguage */ languages: DetectedLanguage[]; } @@ -5807,24 +6689,39 @@ export namespace Browser { * @since Chrome 35 */ export function getUILanguage(): string; - - /** Detects the language of the provided text using CLD. + /** + * 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 */ export function detectLanguage(text: string): Promise; - /** Detects the language of the provided text using CLD. + /** + * 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; + + /** DetectedLanguage object that holds detected ISO language code and its percentage in the input string */ + interface _DetectLanguageReturnResultLanguages { + language: LanguageCode; + /** The percentage of the detected language */ + percentage: number; + } + + /** + * LanguageDetectionResult object that holds detected langugae reliability and array of DetectedLanguage + */ + interface _DetectLanguageReturnResult { + /** CLD detected language reliability */ + isReliable: boolean; + /** array of detectedLanguage */ + languages: _DetectLanguageReturnResultLanguages[]; + } } - //////////////////// - // Identity - //////////////////// /** - * Use the `Browser.identity` API to get OAuth2 access tokens. + * Use the `chrome.identity` API to get OAuth2 access tokens. * * Permissions: "identity" */ @@ -5839,7 +6736,7 @@ export namespace Browser { /** Specifies that Sync is enabled for the primary account. */ SYNC = "SYNC", /** Specifies the existence of a primary account, if any. */ - ANY = "ANY", + ANY = "ANY" } /** @since Chrome 84 */ @@ -5881,7 +6778,6 @@ export namespace Browser { export interface WebAuthFlowDetails { /** The URL that initiates the auth flow. */ url: string; - /** * Whether to launch auth flow in interactive mode. * @@ -5926,7 +6822,6 @@ export namespace Browser { */ export function clearAllCachedAuthTokens(): Promise; export function clearAllCachedAuthTokens(callback: () => void): void; - /** * Retrieves a list of AccountInfo objects describing the accounts present on the profile. * @@ -5934,7 +6829,6 @@ export namespace Browser { */ export function getAccounts(): Promise; export function getAccounts(callback: (accounts: AccountInfo[]) => void): void; - /** * Gets an OAuth2 access token using the client ID and scopes specified in the oauth2 section of manifest.json. * @@ -5948,7 +6842,6 @@ export namespace Browser { export function getAuthToken(details?: TokenDetails): Promise; export function getAuthToken(details: TokenDetails, callback: (result: GetAuthTokenResult) => void): void; export function getAuthToken(callback: (result: GetAuthTokenResult) => void): void; - /** * Retrieves email address and obfuscated gaia id of the user signed into a profile. * @@ -5960,12 +6853,8 @@ export namespace Browser { * Can return its result via Promise since Chrome 105. */ export function getProfileUserInfo(details?: ProfileDetails): Promise; - export function getProfileUserInfo( - details: ProfileDetails, - callback: (userInfo: ProfileUserInfo) => void, - ): void; + export function getProfileUserInfo(details: ProfileDetails, callback: (userInfo: ProfileUserInfo) => void): void; export function getProfileUserInfo(callback: (userInfo: ProfileUserInfo) => void): void; - /** * Removes an OAuth2 access token from the Identity API's token cache. * @@ -5976,7 +6865,6 @@ export namespace Browser { */ export function removeCachedAuthToken(details: InvalidTokenDetails): Promise; export function removeCachedAuthToken(details: InvalidTokenDetails, callback: () => void): void; - /** * Starts an auth flow at the specified URL. * @@ -5989,7 +6877,6 @@ export namespace Browser { */ export function launchWebAuthFlow(details: WebAuthFlowDetails): Promise; export function launchWebAuthFlow(details: WebAuthFlowDetails, callback: (responseUrl?: string) => void): void; - /** * Generates a redirect URL to be used in `launchWebAuthFlow`. * @@ -5997,28 +6884,57 @@ export namespace Browser { * @param path The path appended to the end of the generated URL. */ export function getRedirectURL(path?: string): string; - /** Fired when signin state changes for an account on the user's profile. */ - export const onSignInChanged: Browser.events.Event<(account: AccountInfo, signedIn: boolean) => void>; - } + export const onSignInChanged: chrome.events.Event<(account: AccountInfo, signedIn: boolean) => void>; - //////////////////// - // Idle - //////////////////// - /** - * Use the `Browser.idle` API to detect when the machine's idle state changes. - * - * Permissions: "idle" - */ - export namespace idle { - export type IdleState = "active" | "idle" | "locked"; - export interface IdleStateChangedEvent extends Browser.events.Event<(newState: IdleState) => void> {} + interface _GetAuthTokenDetails { + interactive?: boolean | undefined; + account?: AccountInfo | undefined; + scopes?: string[] | undefined; + } - /** - * 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 - */ + interface _GetProfileUserInfoReturnUserinfo { + email: string; + id: string; + } + + interface _RemoveCachedAuthTokenReturnUserinfo { + email: string; + id: string; + } + + interface _RemoveCachedAuthTokenDetails { + token: string; + } + + interface _LaunchWebAuthFlowDetails { + url: _manifest.HttpURL; + interactive?: boolean | undefined; + } + + /** + * Fired when signin state changes for an account on the user's profile. + * @deprecated Unsupported on Firefox at this time. + */ + const onSignInChanged: WebExtEvent<(account: AccountInfo, signedIn: boolean) => void> | undefined; + } + + /** + * Use the `chrome.idle` API to detect when the machine's idle state changes. + * + * Permissions: "idle" + */ + export namespace idle { + export type IdleState = "active" | "idle" | "locked"; + + export interface IdleStateChangedEvent extends chrome.events.Event<(newState: IdleState) => void> { + } + + /** + * 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 + */ 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. @@ -6026,30 +6942,28 @@ export namespace Browser { * @since Chrome 25 */ 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. */ 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; + /** + * Fired when the system changes to an active or idle state. The event fires with "idle" if the the user has not generated any input for a specified number of seconds, and "active" when the user generates input on an idle system. + */ + const onStateChanged: WebExtEvent<(newState: IdleState) => void>; } - //////////////////// - // Input - IME - //////////////////// /** - * Use the `Browser.input.ime` API to implement a custom IME for Chrome OS. This allows your extension to handle keystrokes, set the composition, and manage the candidate window. + * Use the `chrome.input.ime` API to implement a custom IME for Chrome OS. This allows your extension to handle keystrokes, set the composition, and manage the candidate window. * * Permissions: "input" * @platform ChromeOS only @@ -6119,6 +7033,7 @@ export namespace Browser { * @since Chrome 69 */ export type AutoCapitalizeType = "characters" | "words" | "sentences"; + /** 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. */ @@ -6257,7 +7172,6 @@ export namespace Browser { /** Type of the assistive window. */ export type AssistiveWindowType = "undo"; - /** ID of a button in an assistive window. */ export type AssistiveWindowButton = "undo" | "addToDictionary"; @@ -6371,35 +7285,38 @@ export namespace Browser { windowType: AssistiveWindowType; } - export interface BlurEvent extends Browser.events.Event<(contextID: number) => void> {} + export interface BlurEvent extends chrome.events.Event<(contextID: number) => void> { + } - export interface AssistiveWindowButtonClickedEvent - extends Browser.events.Event<(details: AssistiveWindowButtonClickedDetails) => void> - {} + export interface AssistiveWindowButtonClickedEvent extends chrome.events.Event<(details: AssistiveWindowButtonClickedDetails) => void> { + } - export interface CandidateClickedEvent - extends Browser.events.Event<(engineID: string, candidateID: number, button: string) => void> - {} + export interface CandidateClickedEvent extends chrome.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 KeyEventEvent extends chrome.events.Event<(engineID: string, keyData: KeyboardEvent, requestId: string) => void> { + } - export interface DeactivatedEvent extends Browser.events.Event<(engineID: string) => void> {} + export interface DeactivatedEvent extends chrome.events.Event<(engineID: string) => void> { + } - export interface InputContextUpdateEvent extends Browser.events.Event<(context: InputContext) => void> {} + export interface InputContextUpdateEvent extends chrome.events.Event<(context: InputContext) => void> { + } - export interface ActivateEvent extends Browser.events.Event<(engineID: string, screen: string) => void> {} + export interface ActivateEvent extends chrome.events.Event<(engineID: string, screen: string) => void> { + } - export interface FocusEvent extends Browser.events.Event<(context: InputContext) => void> {} + export interface FocusEvent extends chrome.events.Event<(context: InputContext) => void> { + } - export interface MenuItemActivatedEvent extends Browser.events.Event<(engineID: string, name: string) => void> {} + export interface MenuItemActivatedEvent extends chrome.events.Event<(engineID: string, name: string) => void> { + } - export interface SurroundingTextChangedEvent - extends Browser.events.Event<(engineID: string, surroundingInfo: SurroundingTextInfo) => void> - {} + export interface SurroundingTextChangedEvent extends chrome.events.Event<(engineID: string, surroundingInfo: SurroundingTextInfo) => void> { + } - export interface InputResetEvent extends Browser.events.Event<(engineID: string) => void> {} + export interface InputResetEvent extends chrome.events.Event<(engineID: string) => void> { + } /** * Adds the provided menu items to the language menu when this IME is active. @@ -6407,7 +7324,7 @@ export namespace Browser { export function setMenuItems(parameters: ImeParameters, 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. + * @param callback Called when the operation completes with a boolean indicating if the text was accepted or not. On failure, chrome.runtime.lastError is set. */ export function commitText(parameters: CommitTextParameters, callback?: (success: boolean) => void): void; /** @@ -6417,7 +7334,7 @@ export namespace Browser { 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. + * @param callback Called when the operation completes with a boolean indicating if the text was accepted or not. On failure, chrome.runtime.lastError is set. */ export function setComposition(parameters: CompositionParameters, callback?: (success: boolean) => void): void; /** @@ -6430,52 +7347,37 @@ export namespace Browser { * @param parameters * @param callback Called when the operation completes. */ - export function setAssistiveWindowProperties( - parameters: { + export function setAssistiveWindowProperties(parameters: { contextID: number; - properties: Browser.input.ime.AssistiveWindowProperties; - }, - callback?: (success: boolean) => void, - ): void; + properties: chrome.input.ime.AssistiveWindowProperties; + }, 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. + * @param callback Called when the operation completes. On failure, chrome.runtime.lastError is set. */ - export function setAssistiveWindowButtonHighlighted( - parameters: { + export function setAssistiveWindowButtonHighlighted(parameters: { contextID: number; - buttonID: Browser.input.ime.AssistiveWindowButton; - windowType: Browser.input.ime.AssistiveWindowType; + buttonID: chrome.input.ime.AssistiveWindowButton; + windowType: chrome.input.ime.AssistiveWindowType; announceString?: string | undefined; highlighted: boolean; - }, - callback?: () => void, - ): void; + }, 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. */ - export function setCandidateWindowProperties( - parameters: CandidateWindowParameter, - callback?: (success: boolean) => void, - ): void; + export function setCandidateWindowProperties(parameters: CandidateWindowParameter, 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. + * @param callback Called when the operation completes with a boolean indicating if the text was accepted or not. On failure, chrome.runtime.lastError is set. */ - export function clearComposition( - parameters: ClearCompositionParameters, - callback?: (success: boolean) => void, - ): void; + export function clearComposition(parameters: ClearCompositionParameters, 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 */ - export function setCursorPosition( - parameters: CursorPositionParameters, - callback?: (success: boolean) => void, - ): void; + 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 @@ -6499,7 +7401,6 @@ export namespace Browser { * @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. */ @@ -6530,17 +7431,15 @@ export namespace Browser { export var onReset: InputResetEvent; } - //////////////////// - // Instance ID - //////////////////// /** - * Use `Browser.instanceID` to access the Instance ID service. + * Use `chrome.instanceID` to access the Instance ID service. * * Permissions: "gcm" * @since Chrome 44 */ export namespace instanceID { - export interface TokenRefreshEvent extends Browser.events.Event<() => void> {} + export interface TokenRefreshEvent extends chrome.events.Event<() => void> { + } /** * Resets the app instance identifier and revokes all tokens associated with it. @@ -6564,6 +7463,7 @@ export namespace Browser { */ scope: string; } + /** * Revoked a granted token. * @@ -6571,11 +7471,7 @@ export namespace Browser { * asynchronously, with a Promise (MV3 only). */ export function deleteToken(deleteTokenParams: DeleteTokenParams): Promise; - export function deleteToken( - deleteTokenParams: DeleteTokenParams, - callback: () => void, - ): void; - + export function deleteToken(deleteTokenParams: DeleteTokenParams, callback: () => void): void; /** * Retrieves the time when the InstanceID has been generated. * @@ -6584,7 +7480,6 @@ export namespace Browser { */ export function getCreationTime(): Promise; export function getCreationTime(callback: (creationTime: number) => void): void; - /** * 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. @@ -6603,6 +7498,7 @@ export namespace Browser { */ options?: { [key: string]: string }; } + /** * Return a token that allows the authorized entity to access the service defined by scope. * @@ -6610,44 +7506,34 @@ export namespace Browser { */ export function getToken(getTokenParams: GetTokenParams): Promise; export function getToken(getTokenParams: GetTokenParams, callback: (token: string) => void): void; - export var onTokenRefresh: TokenRefreshEvent; } - //////////////////// - // LoginState - //////////////////// /** - * Use the `Browser.loginState` API to read and monitor the login state. + * Use the `chrome.loginState` API to read and monitor the login state. * * Permissions: "loginState" * @platform ChromeOS only * @since Chrome 78 */ export namespace loginState { - export interface SessionStateChangedEvent extends Browser.events.Event<(sessionState: SessionState) => void> {} + export interface SessionStateChangedEvent extends chrome.events.Event<(sessionState: SessionState) => void> { + } /** Possible profile types. */ export type ProfileType = "SIGNIN_PROFILE" | "USER_PROFILE"; - /** 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. */ export function getProfileType(callback: (profileType: ProfileType) => 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.*/ + /** Dispatched when the session state changes. sessionState is the new session state. */ export const onSessionStateChanged: SessionStateChangedEvent; } - //////////////////// - // Management - //////////////////// /** - * The `Browser.management` API provides ways to manage installed apps and extensions. + * The `chrome.management` API provides ways to manage installed apps and extensions. * * Permissions: "management" */ @@ -6764,13 +7650,17 @@ export namespace Browser { showConfirmDialog?: boolean | undefined; } - export interface ManagementDisabledEvent extends Browser.events.Event<(info: ExtensionInfo) => void> {} + export interface ManagementDisabledEvent extends chrome.events.Event<(info: ExtensionInfo) => void> { + } - export interface ManagementUninstalledEvent extends Browser.events.Event<(id: string) => void> {} + export interface ManagementUninstalledEvent extends chrome.events.Event<(id: string) => void> { + } - export interface ManagementInstalledEvent extends Browser.events.Event<(info: ExtensionInfo) => void> {} + export interface ManagementInstalledEvent extends chrome.events.Event<(info: ExtensionInfo) => void> { + } - export interface ManagementEnabledEvent extends Browser.events.Event<(info: ExtensionInfo) => void> {} + export interface ManagementEnabledEvent extends chrome.events.Event<(info: ExtensionInfo) => void> { + } /** * Enables or disables an app or extension. @@ -6826,18 +7716,13 @@ export namespace Browser { * @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; + 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 * @param manifestStr Extension manifest JSON string. */ - export function getPermissionWarningsByManifest( - manifestStr: string, - callback: (permissionwarnings: string[]) => void, - ): void; + export function getPermissionWarningsByManifest(manifestStr: string, callback: (permissionwarnings: string[]) => void): void; /** * Launches an application. * @param id The extension id of the application. @@ -6955,7 +7840,6 @@ export namespace Browser { * @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; /** Fired when an app or extension has been uninstalled. */ @@ -6964,11 +7848,38 @@ export namespace Browser { export var onInstalled: ManagementInstalledEvent; /** Fired when an app or extension has been enabled. */ export var onEnabled: ManagementEnabledEvent; + + interface _InstallReturnResult { + id: _manifest.ExtensionID; + } + + interface _InstallOptions { + /** URL pointing to the XPI file on addons.mozilla.org or similar. */ + url: _manifest.HttpURL; + /** A hash of the XPI file, using sha256 or stronger. */ + hash?: string | undefined; + } + + interface _UninstallSelfOptions { + /** Whether or not a confirm-uninstall dialog should prompt the user. Defaults to false. */ + showConfirmDialog?: boolean | undefined; + /** The message to display to a user when being asked to confirm removal of the extension. */ + dialogMessage?: string | undefined; + } + + /** Installs and enables a theme extension from the given url. */ + function install(options: _InstallOptions): Promise<_InstallReturnResult>; + + /** Fired when an addon has been disabled. */ + const onDisabled: WebExtEvent<(info: ExtensionInfo) => void>; + /** Fired when an addon has been enabled. */ + const onEnabled: WebExtEvent<(info: ExtensionInfo) => void>; + /** Fired when an addon has been installed. */ + const onInstalled: WebExtEvent<(info: ExtensionInfo) => void>; + /** Fired when an addon has been uninstalled. */ + const onUninstalled: WebExtEvent<(info: ExtensionInfo) => void>; } - //////////////////// - // Networking - //////////////////// /** * Use the networking.config API to authenticate to captive portals. * Permissions: "networking.config" @@ -6991,7 +7902,8 @@ export namespace Browser { Security?: string | undefined; } - export interface CaptivePorttalDetectedEvent extends Browser.events.Event<(networkInfo: NetworkInfo) => void> {} + export interface CaptivePorttalDetectedEvent extends chrome.events.Event<(networkInfo: NetworkInfo) => void> { + } /** * Allows an extension to define network filters for the networks it can handle. A call to this function will remove all filters previously installed by the extension before setting the new list. @@ -7010,16 +7922,12 @@ export namespace Browser { * @param callback Called back when this operation is finished. */ export function finishAuthentication(GUID: string, result: string, callback?: () => void): void; - /** This event fires everytime a captive portal is detected on a network matching any of the currently registered network filters and the user consents to use the extension for authentication. Network filters may be set using the setNetworkFilter. Upon receiving this event the extension should start its authentication attempt with the captive portal. When the extension finishes its attempt, it must call finishAuthentication with the GUID received with this event and the appropriate authentication result. */ export var onCaptivePortalDetected: CaptivePorttalDetectedEvent; } - //////////////////// - // Notifications - //////////////////// /** - * Use the `Browser.notifications` API to create rich notifications using templates and show these notifications to users in the system tray. + * Use the `chrome.notifications` API to create rich notifications using templates and show these notifications to users in the system tray. * * Permissions: "notifications" */ @@ -7094,7 +8002,8 @@ export namespace Browser { * **Note:** This value is required for the {@link notifications.create}() method. */ title?: string; - /** Which type of notification to display. + /** + * Which type of notification to display. * * **Note:** This value is required for the {@link notifications.create}() method. */ @@ -7107,7 +8016,7 @@ export namespace Browser { /** Specifies that the user has elected to show notifications from the app or extension. This is the default at install time. */ GRANTED = "granted", /** Specifies that the user has elected not to show notifications from the app or extension. */ - DENIED = "denied", + DENIED = "denied" } export enum TemplateType { @@ -7118,7 +8027,7 @@ export namespace Browser { /** Contains an icon, title, message, items, and up to two buttons. Users on Mac OS X only see the first item. */ LIST = "list", /** Contains an icon, title, message, progress, and up to two buttons. */ - PROGRESS = "progress", + PROGRESS = "progress" } /** @@ -7129,7 +8038,6 @@ export namespace Browser { */ export function clear(notificationId: string): Promise; export function clear(notificationId: string, callback: (wasCleared: boolean) => void): void; - /** * Creates and displays a notification. * @param notificationId Identifier of the notification. If not set or empty, an ID will automatically be generated. If it matches an existing notification, this method first clears that notification before proceeding with the create operation. The identifier may not be longer than 500 characters. @@ -7141,13 +8049,8 @@ export namespace Browser { */ export function create(notificationId: string, options: NotificationCreateOptions): Promise; export function create(options: NotificationCreateOptions): Promise; - export function create( - notificationId: string, - options: NotificationCreateOptions, - callback: (notificationId: string) => void, - ): void; + export function create(notificationId: string, options: NotificationCreateOptions, callback: (notificationId: string) => void): void; export function create(options: NotificationCreateOptions, callback: (notificationId: string) => void): void; - /** * Retrieves all the notifications of this app or extension. * @@ -7155,7 +8058,6 @@ export namespace Browser { */ export function getAll(): Promise<{ [key: string]: true }>; export function getAll(callback: (notifications: { [key: string]: true }) => void): void; - /** * Retrieves whether the user has enabled notifications from this app or extension. * @@ -7163,7 +8065,6 @@ export namespace Browser { */ export function getPermissionLevel(): Promise<`${PermissionLevel}`>; export function getPermissionLevel(callback: (level: `${PermissionLevel}`) => void): void; - /** * Updates an existing notification. * @param notificationId The id of the notification to be updated. This is returned by {@link notifications.create} method. @@ -7172,34 +8073,134 @@ export namespace Browser { * Can return its result via Promise since Chrome 116 */ export function update(notificationId: string, options: NotificationOptions): Promise; - export function update( - notificationId: string, - options: NotificationOptions, - callback: (wasUpdated: boolean) => void, - ): void; - + export function update(notificationId: string, options: NotificationOptions, callback: (wasUpdated: boolean) => void): void; /** The user pressed a button in the notification. */ export const onButtonClicked: events.Event<(notificationId: string, buttonIndex: number) => void>; - /** The user clicked in a non-button area of the notification. */ export const onClicked: events.Event<(notificationId: string) => void>; - /** The notification closed, either by the system or by user action. */ export const onClosed: events.Event<(notificationId: string, byUser: boolean) => void>; - /** The user changes the permission level. As of Chrome 47, only ChromeOS has UI that dispatches this event. */ export const onPermissionLevelChanged: events.Event<(level: `${PermissionLevel}`) => void>; - /** * The user clicked on a link for the app's notification settings. As of Chrome 47, only ChromeOS has UI that dispatches this event. As of Chrome 65, that UI has been removed from ChromeOS, too. * @deprecated since Chrome 65. Custom notification settings button is no longer supported. */ export const onShowSettings: events.Event<() => void>; + + interface CreateNotificationOptions { + /** Which type of notification to display. */ + type: TemplateType; + /** A URL to the sender's avatar, app icon, or a thumbnail for image notifications. */ + iconUrl?: string | undefined; + /** A URL to the app icon mask. */ + appIconMaskUrl?: string | undefined; + /** Title of the notification (e.g. sender name for email). */ + title: string; + /** Main notification content. */ + message: string; + /** Alternate notification content with a lower-weight font. */ + contextMessage?: string | undefined; + /** Priority ranges from -2 to 2\. -2 is lowest priority. 2 is highest. Zero is default. */ + priority?: number | undefined; + /** A timestamp associated with the notification, in milliseconds past the epoch. */ + eventTime?: number | undefined; + /** + * Text and icons for up to two notification action buttons. + * @deprecated Unsupported on Firefox at this time. + */ + buttons?: _CreateNotificationOptionsButtons[] | undefined; + /** A URL to the image thumbnail for image-type notifications. */ + imageUrl?: string | undefined; + /** Items for multi-item notifications. */ + items?: NotificationItem[] | undefined; + /** Current progress ranges from 0 to 100. */ + progress?: number | undefined; + /** + * Whether to show UI indicating that the app will visibly respond to clicks on the body of a notification. + */ + isClickable?: boolean | undefined; + } + + interface UpdateNotificationOptions { + /** Which type of notification to display. */ + type?: TemplateType | undefined; + /** A URL to the sender's avatar, app icon, or a thumbnail for image notifications. */ + iconUrl?: string | undefined; + /** A URL to the app icon mask. */ + appIconMaskUrl?: string | undefined; + /** Title of the notification (e.g. sender name for email). */ + title?: string | undefined; + /** Main notification content. */ + message?: string | undefined; + /** Alternate notification content with a lower-weight font. */ + contextMessage?: string | undefined; + /** Priority ranges from -2 to 2\. -2 is lowest priority. 2 is highest. Zero is default. */ + priority?: number | undefined; + /** A timestamp associated with the notification, in milliseconds past the epoch. */ + eventTime?: number | undefined; + /** + * Text and icons for up to two notification action buttons. + * @deprecated Unsupported on Firefox at this time. + */ + buttons?: _UpdateNotificationOptionsButtons[] | undefined; + /** A URL to the image thumbnail for image-type notifications. */ + imageUrl?: string | undefined; + /** Items for multi-item notifications. */ + items?: NotificationItem[] | undefined; + /** Current progress ranges from 0 to 100. */ + progress?: number | undefined; + /** + * Whether to show UI indicating that the app will visibly respond to clicks on the body of a notification. + */ + isClickable?: boolean | undefined; + } + + interface _CreateNotificationOptionsButtons { + title: string; + iconUrl?: string | undefined; + } + + interface _UpdateNotificationOptionsButtons { + title: string; + iconUrl?: string | undefined; + } + + /** + * Fired when the notification closed, either by the system or by user action. + * @param notificationId The notificationId of the closed notification. + * @param byUser True if the notification was closed by the user. + */ + const onClosed: WebExtEvent<(notificationId: string, byUser: boolean) => void>; + /** + * Fired when the user clicked in a non-button area of the notification. + * @param notificationId The notificationId of the clicked notification. + */ + const onClicked: WebExtEvent<(notificationId: string) => void>; + /** + * Fired when the user pressed a button in the notification. + * @param notificationId The notificationId of the clicked notification. + * @param buttonIndex The index of the button clicked by the user. + */ + const onButtonClicked: WebExtEvent<(notificationId: string, buttonIndex: number) => void>; + /** + * Fired when the user changes the permission level. + * @param level The new permission level. + * @deprecated Unsupported on Firefox at this time. + */ + const onPermissionLevelChanged: WebExtEvent<(level: PermissionLevel) => void> | undefined; + /** + * Fired when the user clicked on a link for the app's notification settings. + * @deprecated Unsupported on Firefox at this time. + */ + const onShowSettings: WebExtEvent<() => void> | undefined; + /** + * Fired when the notification is shown. + * @param notificationId The notificationId of the shown notification. + */ + const onShown: WebExtEvent<(notificationId: string) => void>; } - //////////////////// - // Offscreen - //////////////////// /** * Use the `offscreen` API to create and manage offscreen documents. * @@ -7238,7 +8239,7 @@ export namespace Browser { /** Specifies that the offscreen document needs to use window.matchMedia. */ MATCH_MEDIA = "MATCH_MEDIA", /** Specifies that the offscreen document needs to use navigator.geolocation. */ - GEOLOCATION = "GEOLOCATION", + GEOLOCATION = "GEOLOCATION" } /** The parameters describing the offscreen document to create. */ @@ -7263,7 +8264,6 @@ export namespace Browser { * @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). @@ -7274,7 +8274,6 @@ export namespace Browser { * @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). @@ -7287,9 +8286,6 @@ export namespace Browser { export function hasDocument(callback: (result: boolean) => void): void; } - //////////////////// - // Omnibox - //////////////////// /** * The omnibox API allows you to register a keyword with Google Chrome's address bar, which is also known as the omnibox. * @@ -7317,26 +8313,26 @@ export namespace Browser { /** The window disposition for the omnibox query. This is the recommended context to display results. */ export type OnInputEnteredDisposition = "currentTab" | "newForegroundTab" | "newBackgroundTab"; - export interface OmniboxInputEnteredEvent - extends Browser.events.Event<(text: string, disposition: OnInputEnteredDisposition) => void> - {} + export interface OmniboxInputEnteredEvent extends chrome.events.Event<(text: string, disposition: OnInputEnteredDisposition) => void> { + } - export interface OmniboxInputChangedEvent - extends Browser.events.Event<(text: string, suggest: (suggestResults: SuggestResult[]) => void) => void> - {} + export interface OmniboxInputChangedEvent extends chrome.events.Event<(text: string, suggest: (suggestResults: SuggestResult[]) => void) => void> { + } - export interface OmniboxInputStartedEvent extends Browser.events.Event<() => void> {} + export interface OmniboxInputStartedEvent extends chrome.events.Event<() => void> { + } - export interface OmniboxInputCancelledEvent extends Browser.events.Event<() => void> {} + export interface OmniboxInputCancelledEvent extends chrome.events.Event<() => void> { + } - export interface OmniboxSuggestionDeletedEvent extends Browser.events.Event<(text: string) => void> {} + export interface OmniboxSuggestionDeletedEvent extends chrome.events.Event<(text: string) => void> { + } /** * 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. * @param suggestion A partial SuggestResult object, without the 'content' parameter. */ export function setDefaultSuggestion(suggestion: Suggestion): void; - /** User has accepted what is typed into the omnibox. */ export var onInputEntered: OmniboxInputEnteredEvent; /** User has changed what is typed into the omnibox. */ @@ -7350,20 +8346,78 @@ export namespace Browser { * @since Chrome 63 */ export var onDeleteSuggestion: OmniboxSuggestionDeletedEvent; + + /** A suggest result. */ + interface DefaultSuggestResult { + /** The text that is displayed in the URL dropdown. */ + description: string; + /** + * An array of style ranges for the description, as provided by the extension. + * @deprecated Unsupported on Firefox at this time. + */ + descriptionStyles?: _DefaultSuggestResultDescriptionStyles[] | undefined; + /** + * An array of style ranges for the description, as provided by ToValue(). + * @deprecated Unsupported on Firefox at this time. + */ + descriptionStylesRaw?: _DefaultSuggestResultDescriptionStylesRaw[] | undefined; + } + + /** The style ranges for the description, as provided by the extension. */ + interface _SuggestResultDescriptionStyles { + offset: number; + /** The style type */ + type: DescriptionStyleType; + length?: number | undefined; + } + + /** The style ranges for the description, as provided by ToValue(). */ + interface _SuggestResultDescriptionStylesRaw { + offset: number; + type: number; + } + + /** The style ranges for the description, as provided by the extension. */ + interface _DefaultSuggestResultDescriptionStyles { + offset: number; + /** The style type */ + type: DescriptionStyleType; + length?: number | undefined; + } + + /** The style ranges for the description, as provided by ToValue(). */ + interface _DefaultSuggestResultDescriptionStylesRaw { + offset: number; + type: number; + } + + /** + * 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. + */ + const onInputStarted: WebExtEvent<() => void>; + /** + * User has changed what is typed into the omnibox. + * @param suggest A callback passed to the onInputChanged event used for sending suggestions back to the browser. + */ + const onInputChanged: WebExtEvent<(text: string, suggest: (suggestResults: SuggestResult[]) => void) => void>; + /** User has accepted what is typed into the omnibox. */ + const onInputEntered: WebExtEvent<(text: string, disposition: OnInputEnteredDisposition) => void>; + /** User has ended the keyword input session without accepting the input. */ + const onInputCancelled: WebExtEvent<() => void>; + /** User has deleted a suggested result. */ + const onDeleteSuggestion: WebExtEvent<(text: string) => void>; } - //////////////////// - // Page Action - //////////////////// /** - * Use the `Browser.pageAction` API to put icons in the main Google Chrome toolbar, to the right of the address bar. Page actions represent actions that can be taken on the current page, but that aren't applicable to all pages. Page actions appear grayed out when inactive. + * Use the `chrome.pageAction` API to put icons in the main Google Chrome toolbar, to the right of the address bar. Page actions represent actions that can be taken on the current page, but that aren't applicable to all pages. Page actions appear grayed out when inactive. * * Manifest: "page_action" * * MV2 only */ export namespace pageAction { - export interface PageActionClickedEvent extends Browser.events.Event<(tab: Browser.tabs.Tab) => void> {} + export interface PageActionClickedEvent extends chrome.events.Event<(tab: chrome.tabs.Tab) => void> { + } export interface TitleDetails { /** The id of the tab for which you want to modify the page action. */ @@ -7440,16 +8494,74 @@ export namespace Browser { * 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; + + /** Information sent when a page action is clicked. */ + interface OnClickData { + /** An array of keyboard modifiers that were held while the menu item was clicked. */ + modifiers: _OnClickDataModifiers[]; + /** An integer value of button by which menu item was clicked. */ + button?: number | undefined; + } + + interface _IsShownDetails { + /** Specify the tab to get the shownness from. */ + tabId: number; + } + + interface _SetTitleDetails { + /** The id of the tab for which you want to modify the page action. */ + tabId: number; + /** The tooltip string. */ + title: string | null; + } + + interface _GetTitleDetails { + /** Specify the tab to get the title from. */ + tabId: number; + } + + interface _SetIconDetails { + /** 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` * 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?: ImageDataType | { + [key: number]: ImageDataType; + } | 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` * 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 | { + [key: number]: string; + } | undefined; + } + + interface _SetPopupDetails { + /** 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. */ + popup: string | null; + } + + interface _GetPopupDetails { + /** Specify the tab to get the popup from. */ + tabId: number; + } + + /** Checks whether the page action is shown. */ + function isShown(details: _IsShownDetails): Promise; + /** Opens the extension page action in the active window. */ + function openPopup(): Promise; + + /** Fired when a page action icon is clicked. This event will not fire if the page action has a popup. */ + const onClicked: WebExtEvent<(tab: tabs.Tab, info?: OnClickData) => void>; } - //////////////////// - // Page Capture - //////////////////// /** - * Use the `Browser.pageCapture` API to save a tab as MHTML. + * Use the `chrome.pageCapture` API to save a tab as MHTML. * * Permissions: "pageCapture" */ @@ -7472,18 +8584,15 @@ export namespace Browser { export function saveAsMHTML(details: SaveDetails): Promise; } - //////////////////// - // Permissions - //////////////////// /** - * Use the `Browser.permissions` API to request declared optional permissions at run time rather than install time, so users understand why the permissions are needed and grant only those that are necessary. + * Use the `chrome.permissions` API to request declared optional permissions at run time rather than install time, so users understand why the permissions are needed and grant only those that are necessary. */ export namespace permissions { export interface Permissions { /** 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?: chrome.runtime.ManifestPermissions[]; } export interface AddHostAccessRequest { @@ -7501,21 +8610,18 @@ export namespace Browser { */ export function addHostAccessRequest(request: AddHostAccessRequest): Promise; export function addHostAccessRequest(request: AddHostAccessRequest, callback: () => void): void; - /** * Checks if the extension has the specified permissions. * Can return its result via Promise in Manifest V3 or later since Chrome 96. */ export function contains(permissions: Permissions): Promise; export function contains(permissions: Permissions, callback: (result: boolean) => void): void; - /** * Gets the extension's current set of permissions. * Can return its result via Promise in Manifest V3 or later since Chrome 96. */ export function getAll(): Promise; export function getAll(callback: (permissions: Permissions) => void): void; - /** * Requests access to the specified permissions, displaying a prompt to the user if necessary. * These permissions must either be defined in the optional_permissions field of the manifest or be required permissions that were withheld by the user. @@ -7526,7 +8632,6 @@ export namespace Browser { */ export function request(permissions: Permissions): Promise; export function request(permissions: Permissions, callback: (granted: boolean) => void): void; - /** * Removes access to the specified permissions. If there are any problems removing the permissions, {@link runtime.lastError} will be set. * Can return its result via Promise in Manifest V3 or later since Chrome 96. @@ -7549,19 +8654,24 @@ export namespace Browser { */ export function removeHostAccessRequest(request: RemoveHostAccessRequest): Promise; export function removeHostAccessRequest(request: RemoveHostAccessRequest, callback: () => void): void; - /** Fired when access to permissions has been removed from the extension. */ - export const onRemoved: Browser.events.Event<(permissions: Permissions) => void>; + export const onRemoved: chrome.events.Event<(permissions: Permissions) => void>; + /** Fired when the extension acquires new permissions. */ + export const onAdded: chrome.events.Event<(permissions: Permissions) => void>; + + interface AnyPermissions { + permissions?: _manifest.Permission[] | undefined; + origins?: _manifest.MatchPattern[] | undefined; + } /** Fired when the extension acquires new permissions. */ - export const onAdded: Browser.events.Event<(permissions: Permissions) => void>; + const onAdded: WebExtEvent<(permissions: Permissions) => void>; + /** Fired when permissions are removed from the extension. */ + const onRemoved: WebExtEvent<(permissions: Permissions) => void>; } - //////////////////// - // Platform Keys - //////////////////// /** - * Use the `Browser.platformKeys` API to access client certificates managed by the platform. If the user or policy grants the permission, an extension can use such a certficate in its custom authentication protocol. E.g. this allows usage of platform managed certificates in third party VPNs (see Browser.vpnProvider). + * Use the `chrome.platformKeys` API to access client certificates managed by the platform. If the user or policy grants the permission, an extension can use such a certficate in its custom authentication protocol. E.g. this allows usage of platform managed certificates in third party VPNs (see chrome.vpnProvider). * * Permissions: "platformKeys" * @platform ChromeOS only @@ -7615,10 +8725,7 @@ export namespace Browser { * This function filters from a list of client certificates the ones that are known to the platform, match request and for which the extension has permission to access the certificate and its private key. If interactive is true, the user is presented a dialog where they can select from matching certificates and grant the extension access to the certificate. The selected/filtered client certificates will be passed to callback. * Parameter matches: The list of certificates that match the request, that the extension has permission for and, if interactive is true, that were selected by the user. */ - export function selectClientCertificates( - details: ClientCertificateSelectDetails, - callback: (matches: Match[]) => void, - ): void; + export function selectClientCertificates(details: ClientCertificateSelectDetails, callback: (matches: Match[]) => void): void; /** * Passes the key pair of certificate for usage with platformKeys.subtleCrypto to callback. * @param certificate The certificate of a Match returned by selectClientCertificates. @@ -7626,11 +8733,7 @@ export namespace Browser { * @param callback The public and private CryptoKey of a certificate which can only be used with platformKeys.subtleCrypto. * Optional parameter privateKey: Might be null if this extension does not have access to it. */ - export function getKeyPair( - certificate: ArrayBuffer, - parameters: { [key: string]: unknown }, - callback: (publicKey: CryptoKey, privateKey: CryptoKey | null) => void, - ): void; + export function getKeyPair(certificate: ArrayBuffer, parameters: { [key: string]: unknown }, callback: (publicKey: CryptoKey, privateKey: CryptoKey | null) => void): void; /** * Passes the key pair of publicKeySpkiDer for usage with platformKeys.subtleCrypto to callback. * @param publicKeySpkiDer A DER-encoded X.509 SubjectPublicKeyInfo, obtained e.g. by calling WebCrypto's exportKey function with format="spki". @@ -7640,27 +8743,17 @@ export namespace Browser { * Optional parameter privateKey: Might be null if this extension does not have access to it. * @since Chrome 85 */ - export function getKeyPairBySpki( - publicKeySpkiDer: ArrayBuffer, - parameters: { [key: string]: unknown }, - callback: (publicKey: CryptoKey, privateKey: CryptoKey | null) => void, - ): void; + export function getKeyPairBySpki(publicKeySpkiDer: ArrayBuffer, parameters: { [key: string]: unknown }, callback: (publicKey: CryptoKey, privateKey: CryptoKey | null) => void): void; /** An implementation of WebCrypto's SubtleCrypto that allows crypto operations on keys of client certificates that are available to this extension. */ export function subtleCrypto(): SubtleCrypto; /** * Checks whether details.serverCertificateChain can be trusted for details.hostname according to the trust settings of the platform. Note: The actual behavior of the trust verification is not fully specified and might change in the future. The API implementation verifies certificate expiration, validates the certification path and checks trust by a known CA. The implementation is supposed to respect the EKU serverAuth and to support subject alternative names. */ - export function verifyTLSServerCertificate( - details: ServerCertificateVerificationDetails, - callback: (result: ServerCertificateVerificationResult) => void, - ): void; + export function verifyTLSServerCertificate(details: ServerCertificateVerificationDetails, callback: (result: ServerCertificateVerificationResult) => void): void; } - //////////////////// - // Power - //////////////////// /** - * Use the `Browser.power` API to override the system's power management features. + * Use the `chrome.power` API to override the system's power management features. * * Permissions: "power" */ @@ -7669,15 +8762,13 @@ export namespace Browser { /** Prevents the display from being turned off or dimmed, or the system from sleeping in response to user inactivity */ DISPLAY = "display", /** Prevents the system from sleeping in response to user inactivity. */ - SYSTEM = "system", + SYSTEM = "system" } /** Requests that power management be temporarily disabled. `level` describes the degree to which power management should be disabled. If a request previously made by the same app is still active, it will be replaced by the new request. */ export function requestKeepAwake(level: `${Level}`): void; - /** Releases a request previously made via requestKeepAwake(). */ export function releaseKeepAwake(): void; - /** * Reports a user activity in order to awake the screen from a dimmed or turned off state or from a screensaver. Exits the screensaver if it is currently active. * Can return its result via Promise in Manifest V3 or later. @@ -7688,11 +8779,8 @@ export namespace Browser { export function reportActivity(callback: () => void): void; } - //////////////////// - // Printer Provider - //////////////////// /** - * The `Browser.printerProvider` API exposes events used by print manager to query printers controlled by extensions, to query their capabilities and to submit print jobs to these printers. + * The `chrome.printerProvider` API exposes events used by print manager to query printers controlled by extensions, to query their capabilities and to submit print jobs to these printers. * * Permissions: "printerProvider" * @since Chrome 44 @@ -7725,23 +8813,19 @@ export namespace Browser { document: Blob; } - export interface PrinterRequestedEvent - extends Browser.events.Event<(resultCallback: (printerInfo: PrinterInfo[]) => void) => void> - {} + export interface PrinterRequestedEvent extends chrome.events.Event<(resultCallback: (printerInfo: PrinterInfo[]) => void) => void> { + } - export interface PrinterInfoRequestedEvent - extends Browser.events.Event<(device: any, resultCallback: (printerInfo?: PrinterInfo) => void) => void> - {} + export interface PrinterInfoRequestedEvent extends chrome.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 CapabilityRequestedEvent extends chrome.events.Event< + (printerId: string, resultCallback: (capabilities: PrinterCapabilities) => void) => void + > { + } - export interface PrintRequestedEvent - extends Browser.events.Event<(printJob: PrintJob, resultCallback: (result: string) => void) => void> - {} + export interface PrintRequestedEvent extends chrome.events.Event<(printJob: PrintJob, resultCallback: (result: string) => void) => void> { + } /** Event fired when print manager requests printers provided by extensions. */ export var onGetPrintersRequested: PrinterRequestedEvent; @@ -7757,16 +8841,13 @@ export namespace Browser { export var onPrintRequested: PrintRequestedEvent; } - //////////////////// - // Printing - //////////////////// /** - * Use the `Browser.printing` API to send print jobs to printers installed on Chromebook. - - * Permissions: "printing" - * @platform ChromeOS only - * @since Chrome 81 - */ + * Use the `chrome.printing` API to send print jobs to printers installed on Chromebook. + * + * Permissions: "printing" + * @platform ChromeOS only + * @since Chrome 81 + */ export namespace printing { export interface GetPrinterInfoResponse { /** Printer capabilities in [CDD format](https://developers.google.com/cloud-print/docs/cdd#cdd-example). The property may be missing. */ @@ -7786,7 +8867,7 @@ export namespace Browser { /** Print job was canceled by the user or via API. */ CANCELED = "CANCELED", /** Print job was printed without any errors. */ - PRINTED = "PRINTED", + PRINTED = "PRINTED" } export interface Printer { @@ -7817,7 +8898,7 @@ export namespace Browser { /** Printer was added by user. */ USER = "USER", /** Printer was added via policy. */ - POLICY = "POLICY", + POLICY = "POLICY" } /** The status of the printer. */ @@ -7843,7 +8924,7 @@ export namespace Browser { /** The SSL certificate is expired. Printer accepts jobs but they fail. */ EXPIRED_CERTIFICATE = "EXPIRED_CERTIFICATE", /** The printer is available. */ - AVAILABLE = "AVAILABLE", + AVAILABLE = "AVAILABLE" } export interface SubmitJobRequest { @@ -7852,7 +8933,7 @@ export namespace Browser { * Supported content types are "application/pdf" and "image/png". The Cloud Job Ticket shouldn't include `FitToPageTicketItem`, `PageRangeTicketItem` and `ReverseOrderTicketItem` fields since they are irrelevant for native printing. `VendorTicketItem` is optional * All other fields must be present. */ - job: Browser.printerProvider.PrintJob; + job: chrome.printerProvider.PrintJob; } export interface SubmitJobResponse { @@ -7867,61 +8948,51 @@ export namespace Browser { /** Sent print job request is accepted. */ OK = "OK", /** Sent print job request is rejected by the user. */ - USER_REJECTED = "USER_REJECTED", + USER_REJECTED = "USER_REJECTED" } /** The maximum number of times that getPrinterInfo can be called per minute. */ export const MAX_GET_PRINTER_INFO_CALLS_PER_MINUTE: 20; - /** The maximum number of times that submitJob can be called per minute. */ export const MAX_SUBMIT_JOB_CALLS_PER_MINUTE: 40; - /** * Cancels previously submitted job. * Can return its result via Promise in Manifest V3 or later since Chrome 100. */ export function cancelJob(jobId: string): Promise; export function cancelJob(jobId: string, callback: () => void): void; - /** * Returns the status of the print job. This call will fail with a runtime error if the print job with the given `jobId` doesn't exist. `jobId`: The id of the print job to return the status of. This should be the same id received in a {@link SubmitJobResponse}. * @since Chrome 135 */ export function getJobStatus(jobId: string): Promise<`${JobStatus}`>; export function getJobStatus(jobId: string, callback: (status: `${JobStatus}`) => void): void; - /** * Returns the status and capabilities of the printer in CDD format. This call will fail with a runtime error if no printers with given id are installed. * Can return its result via Promise in Manifest V3 or later since Chrome 100. */ export function getPrinterInfo(printerId: string): Promise; export function getPrinterInfo(printerId: string, callback: (response: GetPrinterInfoResponse) => void): void; - /** * Returns the list of available printers on the device. This includes manually added, enterprise and discovered printers. * Can return its result via Promise in Manifest V3 or later since Chrome 100. */ export function getPrinters(): Promise; export function getPrinters(callback: (printers: Printer[]) => void): void; - /** * Submits the job for printing. If the extension is not listed in the PrintingAPIExtensionsAllowlist policy, the user is prompted to accept the print job. * Can return its result via Promise in Manifest V3 or later since Chrome 120. */ export function submitJob(request: SubmitJobRequest): Promise; export function submitJob(request: SubmitJobRequest, callback: (response: SubmitJobResponse) => void): void; - /** * Event fired when the status of the job is changed. This is only fired for the jobs created by this extension. */ - export const onJobStatusChanged: Browser.events.Event<(jobId: string, status: `${JobStatus}`) => void>; + export const onJobStatusChanged: chrome.events.Event<(jobId: string, status: `${JobStatus}`) => void>; } - //////////////////// - // Printing Metrics - //////////////////// /** - * Use the `Browser.printingMetrics` API to fetch data about printing usage. + * Use the `chrome.printingMetrics` API to fetch data about printing usage. * * Permissions: "printingMetrics" * @@ -7934,7 +9005,7 @@ export namespace Browser { /** Specifies that black and white mode was used. */ BLACK_AND_WHITE = "BLACK_AND_WHITE", /** Specifies that color mode was used. */ - COLOR = "COLOR", + COLOR = "COLOR" } export enum DuplexMode { @@ -7943,7 +9014,7 @@ export namespace Browser { /** Specifies that two-sided printing was used, flipping on long edge. */ TWO_SIDED_LONG_EDGE = "TWO_SIDED_LONG_EDGE", /** Specifies that two-sided printing was used, flipping on short edge. */ - TWO_SIDED_SHORT_EDGE = "TWO_SIDED_SHORT_EDGE", + TWO_SIDED_SHORT_EDGE = "TWO_SIDED_SHORT_EDGE" } export interface MediaSize { @@ -7972,7 +9043,7 @@ export namespace Browser { /** Specifies that the printer was added by user. */ USER = "USER", /** Specifies that the printer was added via policy. */ - POLICY = "POLICY", + POLICY = "POLICY" } export interface PrintJobInfo { @@ -7990,7 +9061,7 @@ export namespace Browser { * The status of the printer. * @since Chrome 85 */ - printer_status: Browser.printing.PrinterStatus; + printer_status: chrome.printing.PrinterStatus; /** The settings of the print job. */ settings: PrintSettings; /** Source showing who initiated the print job. */ @@ -8012,7 +9083,7 @@ export namespace Browser { /** Specifies that the job was created by extension via Chrome API. */ EXTENSION = "EXTENSION", /** Specifies that the job was created by an Isolated Web App via API. */ - ISOLATED_WEB_APP = "ISOLATED_WEB_APP", + ISOLATED_WEB_APP = "ISOLATED_WEB_APP" } /** Specifies the final status of the print job. */ @@ -8022,7 +9093,7 @@ export namespace Browser { /** Specifies that the print job was canceled by the user or via API. */ CANCELED = "CANCELED", /** Specifies that the print job was printed without any errors. */ - PRINTED = "PRINTED", + PRINTED = "PRINTED" } export interface PrintSettings { @@ -8042,16 +9113,12 @@ export namespace Browser { */ export function getPrintJobs(): Promise; export function getPrintJobs(callback: (jobs: PrintJobInfo[]) => void): void; - /** Event fired when the print job is finished. This includes any of termination statuses: FAILED, CANCELED and PRINTED. */ - export const onPrintJobFinished: Browser.events.Event<(jobInfo: PrintJobInfo) => void>; + export const onPrintJobFinished: chrome.events.Event<(jobInfo: PrintJobInfo) => void>; } - //////////////////// - // Privacy - //////////////////// /** - * Use the `Browser.privacy` API to control usage of the features in Chrome that can affect a user's privacy. This API relies on the ChromeSetting prototype of the type API for getting and setting Chrome's configuration. + * Use the `chrome.privacy` API to control usage of the features in Chrome that can affect a user's privacy. This API relies on the ChromeSetting prototype of the type API for getting and setting Chrome's configuration. * Note: The Chrome Privacy Whitepaper gives background detail regarding the features which this API can control. * * Permissions: "privacy" @@ -8065,164 +9132,159 @@ export namespace Browser { DEFAULT = "default", DEFAULT_PUBLIC_AND_PRIVATE_INTERFACES = "default_public_and_private_interfaces", DEFAULT_PUBLIC_INTERFACE_ONLY = "default_public_interface_only", - DISABLE_NON_PROXIED_UDP = "disable_non_proxied_udp", + DISABLE_NON_PROXIED_UDP = "disable_non_proxied_udp" } /** Settings that enable or disable features that require third-party network services provided by Google and your default search provider. */ export const services: { - /** - * If enabled, Chrome uses a web service to help resolve navigation errors. - * This preference's value is a boolean, defaulting to `true`. - */ - alternateErrorPagesEnabled: Browser.types.ChromeSetting; + /** + * If enabled, Chrome uses a web service to help resolve navigation errors. + * This preference's value is a boolean, defaulting to `true`. + */ + alternateErrorPagesEnabled: chrome.types.ChromeSetting; - /** - * If enabled, Chrome offers to automatically fill in addresses and other form data. - * This preference's value is a boolean, defaulting to `true`. - * @since Chrome 70 - */ - autofillAddressEnabled: Browser.types.ChromeSetting; + /** + * If enabled, Chrome offers to automatically fill in addresses and other form data. + * This preference's value is a boolean, defaulting to `true`. + * @since Chrome 70 + */ + autofillAddressEnabled: chrome.types.ChromeSetting; - /** - * If enabled, Chrome offers to automatically fill in credit card forms. - * This preference's value is a boolean, defaulting to `true`. - * @since Chrome 70 - */ - autofillCreditCardEnabled: Browser.types.ChromeSetting; + /** + * If enabled, Chrome offers to automatically fill in credit card forms. + * This preference's value is a boolean, defaulting to `true`. + * @since Chrome 70 + */ + autofillCreditCardEnabled: chrome.types.ChromeSetting; - /** - * If enabled, Chrome offers to automatically fill in forms. - * This preference's value is a boolean, defaulting to `true`. - * @deprecated since Chrome 70. Please use privacy.services.autofillAddressEnabled and privacy.services.autofillCreditCardEnabled. This remains for backward compatibility in this release and will be removed in the future */ - autofillEnabled: Browser.types.ChromeSetting; + /** + * If enabled, Chrome offers to automatically fill in forms. + * This preference's value is a boolean, defaulting to `true`. + * @deprecated since Chrome 70. Please use privacy.services.autofillAddressEnabled and privacy.services.autofillCreditCardEnabled. This remains for backward compatibility in this release and will be removed in the future */ + autofillEnabled: chrome.types.ChromeSetting; - /** - * If enabled, the password manager will ask if you want to save passwords. - * This preference's value is a boolean, defaulting to `true`. - */ - passwordSavingEnabled: Browser.types.ChromeSetting; + /** + * If enabled, the password manager will ask if you want to save passwords. + * This preference's value is a boolean, defaulting to `true`. + */ + passwordSavingEnabled: chrome.types.ChromeSetting; - /** - * If enabled, Chrome does its best to protect you from phishing and malware. - * This preference's value is a boolean, defaulting to `true`. - */ - safeBrowsingEnabled: Browser.types.ChromeSetting; + /** + * If enabled, Chrome does its best to protect you from phishing and malware. + * This preference's value is a boolean, defaulting to `true`. + */ + safeBrowsingEnabled: chrome.types.ChromeSetting; - /** - * If enabled, Chrome will send additional information to Google when SafeBrowsing blocks a page, such as the content of the blocked page. - * This preference's value is a boolean, defaulting to `false`. - */ - safeBrowsingExtendedReportingEnabled: Browser.types.ChromeSetting; + /** + * If enabled, Chrome will send additional information to Google when SafeBrowsing blocks a page, such as the content of the blocked page. + * This preference's value is a boolean, defaulting to `false`. + */ + safeBrowsingExtendedReportingEnabled: chrome.types.ChromeSetting; - /** - * If enabled, Chrome sends the text you type into the Omnibox to your default search engine, which provides predictions of websites and searches that are likely completions of what you've typed so far. - * This preference's value is a boolean, defaulting to `true`. - */ - searchSuggestEnabled: Browser.types.ChromeSetting; - - /** - * If enabled, Chrome uses a web service to help correct spelling errors. - * This preference's value is a boolean, defaulting to `false`. - */ - spellingServiceEnabled: Browser.types.ChromeSetting; + /** + * If enabled, Chrome sends the text you type into the Omnibox to your default search engine, which provides predictions of websites and searches that are likely completions of what you've typed so far. + * This preference's value is a boolean, defaulting to `true`. + */ + searchSuggestEnabled: chrome.types.ChromeSetting; - /** - * If enabled, Chrome offers to translate pages that aren't in a language you read. - * This preference's value is a boolean, defaulting to `true`. - */ - translationServiceEnabled: Browser.types.ChromeSetting; - }; + /** + * If enabled, Chrome uses a web service to help correct spelling errors. + * This preference's value is a boolean, defaulting to `false`. + */ + spellingServiceEnabled: chrome.types.ChromeSetting; + /** + * If enabled, Chrome offers to translate pages that aren't in a language you read. + * This preference's value is a boolean, defaulting to `true`. + */ + translationServiceEnabled: chrome.types.ChromeSetting; + }; /** Settings that influence Chrome's handling of network connections in general. */ export const network: { - /** - * If enabled, Chrome attempts to speed up your web browsing experience by pre-resolving DNS entries and preemptively opening TCP and SSL connections to servers. - * This preference only affects actions taken by Chrome's internal prediction service. It does not affect webpage-initiated prefectches or preconnects. - * This preference's value is a boolean, defaulting to `true`. - */ - networkPredictionEnabled: Browser.types.ChromeSetting; - - /** - * Allow users to specify the media performance/privacy tradeoffs which impacts how WebRTC traffic will be routed and how much local address information is exposed. - * This preference's value is of type IPHandlingPolicy, defaulting to `default`. - * @since Chrome 48 - */ - webRTCIPHandlingPolicy: Browser.types.ChromeSetting<`${IPHandlingPolicy}`>; - }; + /** + * If enabled, Chrome attempts to speed up your web browsing experience by pre-resolving DNS entries and preemptively opening TCP and SSL connections to servers. + * This preference only affects actions taken by Chrome's internal prediction service. It does not affect webpage-initiated prefectches or preconnects. + * This preference's value is a boolean, defaulting to `true`. + */ + networkPredictionEnabled: chrome.types.ChromeSetting; + /** + * Allow users to specify the media performance/privacy tradeoffs which impacts how WebRTC traffic will be routed and how much local address information is exposed. + * This preference's value is of type IPHandlingPolicy, defaulting to `default`. + * @since Chrome 48 + */ + webRTCIPHandlingPolicy: chrome.types.ChromeSetting<`${IPHandlingPolicy}`>; + }; /** Settings that determine what information Chrome makes available to websites. */ export const websites: { - /** - * If disabled, the Attribution Reporting API and Private Aggregation API are deactivated. - * The value of this preference is of type boolean, and the default value is `true`. - * Extensions may only disable these APIs by setting the value to `false`. If you try setting these APIs to `true`, it will throw an error. - * @since Chrome 111 - */ - adMeasurementEnabled: Browser.types.ChromeSetting; + /** + * If disabled, the Attribution Reporting API and Private Aggregation API are deactivated. + * The value of this preference is of type boolean, and the default value is `true`. + * Extensions may only disable these APIs by setting the value to `false`. If you try setting these APIs to `true`, it will throw an error. + * @since Chrome 111 + */ + adMeasurementEnabled: chrome.types.ChromeSetting; - /** - * If enabled, Chrome sends 'Do Not Track' (`DNT: 1`) header with your requests. - * The value of this preference is of type boolean, and the default value is `false`. - * @since Chrome 65 - */ - doNotTrackEnabled: Browser.types.ChromeSetting; + /** + * If enabled, Chrome sends 'Do Not Track' (`DNT: 1`) header with your requests. + * The value of this preference is of type boolean, and the default value is `false`. + * @since Chrome 65 + */ + doNotTrackEnabled: chrome.types.ChromeSetting; - /** - * If disabled, the Fledge API is deactivated. - * The value of this preference is of type boolean, and the default value is `true`. - * Extensions may only disable this API by setting the value to `false`. If you try setting this API to `true`, it will throw an error. - * @since Chrome 111 - */ - fledgeEnabled: Browser.types.ChromeSetting; + /** + * If disabled, the Fledge API is deactivated. + * The value of this preference is of type boolean, and the default value is `true`. + * Extensions may only disable this API by setting the value to `false`. If you try setting this API to `true`, it will throw an error. + * @since Chrome 111 + */ + fledgeEnabled: chrome.types.ChromeSetting; - /** - * If enabled, Chrome sends auditing pings when requested by a website (``). - * The value of this preference is of type boolean, and the default value is `true`. - */ - hyperlinkAuditingEnabled: Browser.types.ChromeSetting; + /** + * If enabled, Chrome sends auditing pings when requested by a website (``). + * The value of this preference is of type boolean, and the default value is `true`. + */ + hyperlinkAuditingEnabled: chrome.types.ChromeSetting; - /** - * If enabled, Chrome provides a unique ID to plugins in order to run protected content. - * The value of this preference is of type boolean, and the default value is `true`. - * @platform Windows and ChromeOS only - */ - protectedContentEnabled: Browser.types.ChromeSetting; + /** + * If enabled, Chrome provides a unique ID to plugins in order to run protected content. + * The value of this preference is of type boolean, and the default value is `true`. + * @platform Windows and ChromeOS only + */ + protectedContentEnabled: chrome.types.ChromeSetting; - /** - * If enabled, Chrome sends `referer` headers with your requests. Yes, the name of this preference doesn't match the misspelled header. No, we're not going to change it. - * The value of this preference is of type boolean, and the default value is `true`. - */ - referrersEnabled: Browser.types.ChromeSetting; + /** + * If enabled, Chrome sends `referer` headers with your requests. Yes, the name of this preference doesn't match the misspelled header. No, we're not going to change it. + * The value of this preference is of type boolean, and the default value is `true`. + */ + referrersEnabled: chrome.types.ChromeSetting; - /** - * If disabled, Related Website Sets is deactivated. - * The value of this preference is of type boolean, and the default value is `true`. - * Extensions may only disable this API by setting the value to `false`. If you try setting this API to `true`, it will throw an error. - * @since Chrome 121 - */ - relatedWebsiteSetsEnabled: Browser.types.ChromeSetting; + /** + * If disabled, Related Website Sets is deactivated. + * The value of this preference is of type boolean, and the default value is `true`. + * Extensions may only disable this API by setting the value to `false`. If you try setting this API to `true`, it will throw an error. + * @since Chrome 121 + */ + relatedWebsiteSetsEnabled: chrome.types.ChromeSetting; - /** - * If disabled, Chrome blocks third-party sites from setting cookies. - * The value of this preference is of type boolean, and the default value is `true`. - */ - thirdPartyCookiesAllowed: Browser.types.ChromeSetting; + /** + * If disabled, Chrome blocks third-party sites from setting cookies. + * The value of this preference is of type boolean, and the default value is `true`. + */ + thirdPartyCookiesAllowed: chrome.types.ChromeSetting; - /** - * If disabled, the Topics API is deactivated. - * The value of this preference is of type boolean, and the default value is `true`. - * Extensions may only disable this API by setting the value to `false`. If you try setting this API to `true`, it will throw an error. - * @since Chrome 111 - */ - topicsEnabled: Browser.types.ChromeSetting; - }; + /** + * If disabled, the Topics API is deactivated. + * The value of this preference is of type boolean, and the default value is `true`. + * Extensions may only disable this API by setting the value to `false`. If you try setting this API to `true`, it will throw an error. + * @since Chrome 111 + */ + topicsEnabled: chrome.types.ChromeSetting; + }; } - //////////////////// - // Proxy - //////////////////// /** - * Use the `Browser.proxy` API to manage Chrome's proxy settings. This API relies on the ChromeSetting prototype of the type API for getting and setting the proxy configuration. + * Use the `chrome.proxy` API to manage Chrome's proxy settings. This API relies on the ChromeSetting prototype of the type API for getting and setting the proxy configuration. * * Permissions: "proxy" */ @@ -8288,18 +9350,67 @@ export namespace Browser { fatal: boolean; } - export interface ProxyErrorEvent extends Browser.events.Event<(details: ErrorDetails) => void> {} + export interface ProxyErrorEvent extends chrome.events.Event<(details: ErrorDetails) => void> { + } - export var settings: Browser.types.ChromeSetting; + export var settings: chrome.types.ChromeSetting; /** Notifies about proxy errors. */ export var onProxyError: ProxyErrorEvent; + + interface _OnRequestDetails { + /** + * 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; + url: string; + /** Standard HTTP method. */ + method: string; + /** + * 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; + /** ID of frame that wraps the frame which sent the request. Set to -1 if no parent frame exists. */ + parentFrameId: number; + /** True for private browsing requests. */ + incognito?: boolean | undefined; + /** The cookie store ID of the contextual identity. */ + cookieStoreId?: string | undefined; + /** URL of the resource that triggered this request. */ + originUrl?: string | undefined; + /** URL of the page into which the requested resource will be loaded. */ + documentUrl?: string | undefined; + /** 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; + /** How the requested resource will be used. */ + type: webRequest.ResourceType; + /** The time when this signal is triggered, in milliseconds since the epoch. */ + timeStamp: number; + /** Indicates if this response was fetched from disk cache. */ + fromCache: boolean; + /** The HTTP request headers that are going to be sent out with this request. */ + requestHeaders?: webRequest.HttpHeaders | undefined; + /** Url classification if the request has been classified. */ + urlClassification: webRequest.UrlClassification; + /** Indicates if this request and its content window hierarchy is third party. */ + thirdParty: boolean; + } + + interface _ProxyOnRequestEvent void> { + addListener(cb: TCallback, filter: webRequest.RequestFilter, extraInfoSpec?: Array<"requestHeaders">): void; + removeListener(cb: TCallback): void; + hasListener(cb: TCallback): boolean; + } + + /** Configures proxy settings. This setting's value is an object of type ProxyConfig. */ + const settings: types.Setting; + /** Fired when proxy data is needed for a request. */ + const onRequest: _ProxyOnRequestEvent; + /** Notifies about errors caused by the invalid use of the proxy API. */ + const onError: WebExtEvent<(error: Error) => void>; } - //////////////////// - // ReadingList - //////////////////// /** - * Use the `Browser.readingList` API to read from and modify the items in the Reading List. + * Use the `chrome.readingList` API to read from and modify the items in the Reading List. * * Permissions: "readingList" * @since Chrome 120, MV3 @@ -8358,7 +9469,6 @@ export namespace Browser { */ 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 @@ -8367,7 +9477,6 @@ export namespace Browser { */ 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 @@ -8376,7 +9485,6 @@ export namespace Browser { */ 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 @@ -8385,31 +9493,25 @@ export namespace Browser { */ 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>; - + export const onEntryAdded: chrome.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>; - + export const onEntryRemoved: chrome.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>; + export const onEntryUpdated: chrome.events.Event<(entry: ReadingListEntry) => void>; } - //////////////////// - // Search - //////////////////// /** - * Use the `Browser.search` API to search via the default provider. + * Use the `chrome.search` API to search via the default provider. * * Permissions: "search" * @since Chrome 87 @@ -8418,7 +9520,7 @@ export namespace Browser { export type Disposition = "CURRENT_TAB" | "NEW_TAB" | "NEW_WINDOW"; export interface QueryInfo { - /** Location where search results should be displayed. CURRENT_TAB is the default. */ + /** 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; @@ -8431,20 +9533,51 @@ export namespace Browser { * @param options search configuration options. */ export function query(options: QueryInfo, callback: () => void): void; - /** * 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. */ export function query(options: QueryInfo): Promise; + + /** An object encapsulating a search engine */ + interface SearchEngine { + name: string; + isDefault: boolean; + alias?: string | undefined; + favIconUrl?: string | undefined; + } + + interface _SearchSearchProperties { + /** Terms to search for. */ + query: string; + /** Search engine to use. Uses the default if not specified. */ + engine?: string | undefined; + /** Location where search results should be displayed. NEW_TAB is the default. */ + disposition?: Disposition | undefined; + /** + * The ID of the tab for the search results. If not specified, a new tab is created, unless disposition is set. tabId cannot be used with disposition. + */ + tabId?: number | undefined; + } + + interface _QueryQueryInfo { + /** String to query with the default search provider. */ + text: string; + /** 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?: number | undefined; + } + + /** Gets a list of search engines. */ + function get(): Promise; + /** Perform a search. */ + function search(searchProperties: _SearchSearchProperties): Promise; } - //////////////////// - // Serial - //////////////////// /** - * Use the Browser.serial API to read from and write to a device connected to a serial port. + * Use the chrome.serial API to read from and write to a device connected to a serial port. * Permissions: "enterprise.serial" * @since Chrome 29 * Important: This API works only on Chrome OS. @@ -8452,21 +9585,21 @@ export namespace Browser { */ export namespace serial { export const DataBits: { - SEVEN: "seven"; - EIGHT: "eight"; - }; + SEVEN: "seven"; + EIGHT: "eight"; + }; export const ParityBit: { - NO: "no"; - ODD: "odd"; - EVEN: "even"; - }; + NO: "no"; + ODD: "odd"; + EVEN: "even"; + }; export const StopBits: { - ONE: "one"; - TWO: "two"; - }; + ONE: "one"; + TWO: "two"; + }; export interface DeviceInfo { - /** The device's system path. This should be passed as the path argument to Browser.serial.connect in order to connect to this device. */ + /** The device's system path. This should be passed as the path argument to chrome.serial.connect in order to connect to this device. */ path: string; /** Optional. A PCI or USB vendor ID if one can be determined for the underlying device. */ vendorId?: number | undefined; @@ -8491,8 +9624,10 @@ export namespace Browser { receiveTimeout?: number | undefined; /** See ConnectionOptions.sendTimeout */ sendTimeout?: number | undefined; - /** Optional. See ConnectionOptions.bitrate. - * This field may be omitted or inaccurate if a non-standard bitrate is in use, or if an error occurred while querying the underlying device. */ + /** + * Optional. See ConnectionOptions.bitrate. + * This field may be omitted or inaccurate if a non-standard bitrate is in use, or if an error occurred while querying the underlying device. + */ bitrate?: number | undefined; /** Optional. See ConnectionOptions.dataBits. This field may be omitted if an error occurred while querying the underlying device. */ dataBits?: typeof DataBits[keyof typeof DataBits] | undefined; @@ -8505,18 +9640,22 @@ export namespace Browser { } export interface ConnectionOptions { - /** Optional. Flag indicating whether or not the connection should be left open when the application is suspended (see Manage App Lifecycle: https://developer.chrome.com/apps/app_lifecycle). - * The default value is "false." When the application is loaded, any serial connections previously opened with persistent=true can be fetched with getConnections. */ + /** + * Optional. Flag indicating whether or not the connection should be left open when the application is suspended (see Manage App Lifecycle: https://developer.chrome.com/apps/app_lifecycle). + * The default value is "false." When the application is loaded, any serial connections previously opened with persistent=true can be fetched with getConnections. + */ persistent?: boolean | undefined; /** Optional. An application-defined string to associate with the connection. */ name?: string | undefined; /** Optional. The size of the buffer used to receive data. The default value is 4096. */ bufferSize?: number | undefined; - /** Optional. The requested bitrate of the connection to be opened. + /** + * Optional. The requested bitrate of the connection to be opened. * For compatibility with the widest range of hardware, this number should match one of commonly-available bitrates, * such as 110, 300, 1200, 2400, 4800, 9600, 14400, 19200, 38400, 57600, 115200. * There is no guarantee, of course, that the device connected to the serial port will support the requested bitrate, even if the port itself supports that bitrate. - * 9600 will be passed by default. */ + * 9600 will be passed by default. + */ bitrate?: number | undefined; /** Optional. "eight" will be passed by default. */ dataBits?: typeof DataBits[keyof typeof DataBits] | undefined; @@ -8526,13 +9665,17 @@ export namespace Browser { stopBits?: typeof StopBits[keyof typeof StopBits] | undefined; /** Optional. Flag indicating whether or not to enable RTS/CTS hardware flow control. Defaults to false. */ ctsFlowControl?: boolean | undefined; - /** Optional. The maximum amount of time (in milliseconds) to wait for new data before raising an onReceiveError event with a "timeout" error. + /** + * Optional. The maximum amount of time (in milliseconds) to wait for new data before raising an onReceiveError event with a "timeout" error. * If zero, receive timeout errors will not be raised for the connection. - * Defaults to 0. */ + * Defaults to 0. + */ receiveTimeout?: number | undefined; - /** Optional. The maximum amount of time (in milliseconds) to wait for a send operation to complete before calling the callback with a "timeout" error. + /** + * Optional. The maximum amount of time (in milliseconds) to wait for a send operation to complete before calling the callback with a "timeout" error. * If zero, send timeout errors will not be triggered. - * Defaults to 0. */ + * Defaults to 0. + */ sendTimeout?: number | undefined; } @@ -8542,7 +9685,6 @@ export namespace Browser { * @param callback Called with the list of DeviceInfo objects. */ export function getDevices(callback: (ports: DeviceInfo[]) => void): void; - /** * @since Chrome 33 * @description Connects to a given serial port. @@ -8550,12 +9692,7 @@ export namespace Browser { * @param options Port configuration options. * @param callback Called when the connection has been opened. */ - export function connect( - path: string, - options: ConnectionOptions, - callback: (connectionInfo: ConnectionInfo) => void, - ): void; - + export function connect(path: string, options: ConnectionOptions, callback: (connectionInfo: ConnectionInfo) => void): void; /** * @since Chrome 33 * @description Update the option settings on an open serial port connection. @@ -8563,12 +9700,7 @@ export namespace Browser { * @param options Port configuration options. * @param callback Called when the configuration has completed. */ - export function update( - connectionId: number, - options: ConnectionOptions, - callback: (result: boolean) => void, - ): void; - + export function update(connectionId: number, options: ConnectionOptions, callback: (result: boolean) => void): void; /** * @since Chrome 33 * @description Disconnects from a serial port. @@ -8576,7 +9708,6 @@ export namespace Browser { * @param callback Called when the connection has been closed. */ export function disconnect(connectionId: number, callback: (result: boolean) => void): void; - /** * @since Chrome 33 * @description Pauses or unpauses an open connection. @@ -8585,21 +9716,18 @@ export namespace Browser { * @param callback Called when the connection has been successfully paused or unpaused. */ export function setPaused(connectionId: number, paused: boolean, callback: () => void): void; - /** * @since Chrome 33 * @description Retrieves the state of a given connection. * @param callback Called with connection state information when available. */ export function getInfo(callback: (connectionInfos: ConnectionInfo[]) => void): void; - /** * @since Chrome 33 * @description Retrieves the list of currently opened serial port connections owned by the application. * @param callback Called with the list of connections when available. */ export function getConnections(callback: (connectionInfos: ConnectionInfo[]) => void): void; - /** * @since Chrome 33 * @description Writes data to the given connection. @@ -8608,21 +9736,18 @@ export namespace Browser { * @param callback Called when the operation has completed. */ export function send(connectionId: number, data: ArrayBuffer, callback: (sendInfo: object) => void): void; - /** * @description Flushes all bytes in the given connection's input and output buffers. * @param connectionId The id of the connection. * @param callback */ export function flush(connectionId: number, callback: (result: boolean) => void): void; - /** * @description Retrieves the state of control signals on a given connection. * @param connectionId The id of the connection. * @param callback Called when the control signals are available. */ export function getControlSignals(connectionId: number, callback: (signals: object) => void): void; - /** * @description Sets the state of control signals on a given connection. * @param connectionId The id of the connection. @@ -8631,12 +9756,7 @@ export namespace Browser { * boolean: (optional) rts - RTS (Request To Send). * @param callback Called once the control signals have been set. */ - export function setControlSignals( - connectionId: number, - signals: object, - callback: (result: boolean) => void, - ): void; - + export function setControlSignals(connectionId: number, signals: object, callback: (result: boolean) => void): void; /** * @since Chrome 45 * @description Suspends character transmission on a given connection and places the transmission line in a break state until the clearBreak is called. @@ -8644,7 +9764,6 @@ export namespace Browser { * @param callback */ export function setBreak(connectionId: number, callback: (result: boolean) => void): void; - /** * @since Chrome 45 * @description Restore character transmission on a given connection and place the transmission line in a nonbreak state. @@ -8672,25 +9791,25 @@ export namespace Browser { export namespace serial.onReceiveError { export const OnReceiveErrorEnum: { - /* The connection was disconnected. */ - disconnected: "disconnected"; - /* No data has been received for receiveTimeout milliseconds. */ - timeout: "timeout"; - /* The device was most likely disconnected from the host. */ - device_lost: "device_lost"; - /* The device detected a break condition. */ - break: "break"; - /* The device detected a framing error. */ - frame_error: "frame_error"; - /* A character-buffer overrun has occurred. The next character is lost. */ - overrun: "overrun"; - /* An input buffer overflow has occurred. There is either no room in the input buffer, or a character was received after the end-of-file (EOF) character. */ - buffer_overflow: "buffer_overflow"; - /* The device detected a parity error. */ - parity_error: "parity_error"; - /* A system error occurred and the connection may be unrecoverable. */ - system_error: "system_error"; - }; + /* The connection was disconnected. */ + disconnected: "disconnected"; + /* No data has been received for receiveTimeout milliseconds. */ + timeout: "timeout"; + /* The device was most likely disconnected from the host. */ + device_lost: "device_lost"; + /* The device detected a break condition. */ + break: "break"; + /* The device detected a framing error. */ + frame_error: "frame_error"; + /* A character-buffer overrun has occurred. The next character is lost. */ + overrun: "overrun"; + /* An input buffer overflow has occurred. There is either no room in the input buffer, or a character was received after the end-of-file (EOF) character. */ + buffer_overflow: "buffer_overflow"; + /* The device detected a parity error. */ + parity_error: "parity_error"; + /* A system error occurred and the connection may be unrecoverable. */ + system_error: "system_error"; + }; export interface OnReceiveErrorInfo { /** The connection identifier. */ @@ -8708,27 +9827,21 @@ export namespace Browser { export function addListener(callback: (info: OnReceiveErrorInfo) => void): void; } - type DocumentLifecycle = "prerender" | "active" | "cached" | "pending_deletion"; - type FrameType = "outermost_frame" | "fenced_frame" | "sub_frame"; - - //////////////////// - // Runtime - //////////////////// /** - * Use the `Browser.runtime` API to retrieve the service worker, return details about the manifest, and listen for and respond to events in the extension lifecycle. You can also use this API to convert the relative path of URLs to fully-qualified URLs. + * Use the `chrome.runtime` API to retrieve the service worker, return details about the manifest, and listen for and respond to events in the extension lifecycle. You can also use this API to convert the relative path of URLs to fully-qualified URLs. */ export namespace runtime { /** This will be defined during an API method callback if there was an error */ export var lastError: LastError | undefined; /** The ID of the extension/app. */ export var id: string; - /** https://developer.chrome.com/docs/extensions/reference/api/runtime#type-PlatformOs */ export type PlatformOs = "mac" | "win" | "android" | "cros" | "linux" | "openbsd" | "fuchsia"; /** https://developer.chrome.com/docs/extensions/reference/api/runtime#type-PlatformArch */ export type PlatformArch = "arm" | "arm64" | "x86-32" | "x86-64" | "mips" | "mips64"; /** https://developer.chrome.com/docs/extensions/reference/api/runtime#type-PlatformNaclArch */ export type PlatformNaclArch = "arm" | "x86-32" | "x86-64" | "mips" | "mips64"; + /** https://developer.chrome.com/docs/extensions/reference/api/runtime#type-ContextType */ export enum ContextType { TAB = "TAB", @@ -8736,18 +9849,19 @@ export namespace Browser { BACKGROUND = "BACKGROUND", OFFSCREEN_DOCUMENT = "OFFSCREEN_DOCUMENT", SIDE_PANEL = "SIDE_PANEL", - DEVELOPER_TOOLS = "DEVELOPER_TOOLS", + DEVELOPER_TOOLS = "DEVELOPER_TOOLS" } + /** https://developer.chrome.com/docs/extensions/reference/api/runtime#type-OnInstalledReason */ export enum OnInstalledReason { INSTALL = "install", UPDATE = "update", CHROME_UPDATE = "chrome_update", - SHARED_MODULE_UPDATE = "shared_module_update", + SHARED_MODULE_UPDATE = "shared_module_update" } export interface LastError { - /** Optional. Details about the error which occurred. */ + /** Optional. Details about the error which occurred. */ message?: string | undefined; } @@ -8837,8 +9951,9 @@ export namespace Browser { /** The ID of the extension or app that opened the connection, if any. */ id?: string | undefined; /** The tabs.Tab which opened the connection, if any. This property will only be present when the connection was opened from a tab (including content scripts), and only if the receiver is an extension, not an app. */ - tab?: Browser.tabs.Tab | undefined; - /** The name of the native application that opened the connection, if any. + tab?: chrome.tabs.Tab | undefined; + /** + * The name of the native application that opened the connection, if any. * @since Chrome 74 */ nativeApplication?: string | undefined; @@ -8866,7 +9981,7 @@ export namespace Browser { * The lifecycle the document that opened the connection is in at the time the port was created. Note that the lifecycle state of the document may have changed since port creation. * @since Chrome 106 */ - documentLifecycle?: DocumentLifecycle | undefined; + documentLifecycle?: extensionTypes.DocumentLifecycle | undefined; /** * A UUID of the document that opened the connection. * @since Chrome 106 @@ -8933,27 +10048,31 @@ export namespace Browser { version: string; } - export interface PortDisconnectEvent extends Browser.events.Event<(port: Port) => void> {} + export interface PortDisconnectEvent extends chrome.events.Event<(port: Port) => void> { + } - export interface PortMessageEvent extends Browser.events.Event<(message: any, port: Port) => void> {} + export interface PortMessageEvent extends chrome.events.Event<(message: any, port: Port) => void> { + } - export interface ExtensionMessageEvent extends - Browser.events.Event< - (message: any, sender: MessageSender, sendResponse: (response?: any) => void) => void - > - {} + export interface ExtensionMessageEvent extends chrome.events.Event< + (message: any, sender: MessageSender, sendResponse: (response?: any) => void) => void + > { + } - export interface ExtensionConnectEvent extends Browser.events.Event<(port: Port) => void> {} + export interface ExtensionConnectEvent extends chrome.events.Event<(port: Port) => void> { + } - export interface RuntimeInstalledEvent extends Browser.events.Event<(details: InstalledDetails) => void> {} + export interface RuntimeInstalledEvent extends chrome.events.Event<(details: InstalledDetails) => void> { + } - export interface RuntimeEvent extends Browser.events.Event<() => void> {} + export interface RuntimeEvent extends chrome.events.Event<() => void> { + } - export interface RuntimeRestartRequiredEvent extends Browser.events.Event<(reason: string) => void> {} + export interface RuntimeRestartRequiredEvent extends chrome.events.Event<(reason: string) => void> { + } - export interface RuntimeUpdateAvailableEvent - extends Browser.events.Event<(details: UpdateAvailableDetails) => void> - {} + export interface RuntimeUpdateAvailableEvent extends chrome.events.Event<(details: UpdateAvailableDetails) => void> { + } export interface ManifestIcons { [size: number]: string; @@ -8966,105 +10085,103 @@ export namespace Browser { } /** Source: https://developer.chrome.com/docs/extensions/reference/permissions-list */ - export type ManifestPermissions = - | "accessibilityFeatures.modify" - | "accessibilityFeatures.read" - | "activeTab" - | "alarms" - | "audio" - | "background" - | "bookmarks" - | "browsingData" - | "certificateProvider" - | "clipboardRead" - | "clipboardWrite" - | "contentSettings" - | "contextMenus" - | "cookies" - | "debugger" - | "declarativeContent" - | "declarativeNetRequest" - | "declarativeNetRequestFeedback" - | "declarativeNetRequestWithHostAccess" - | "declarativeWebRequest" - | "desktopCapture" - | "documentScan" - | "downloads" - | "downloads.open" - | "downloads.shelf" - | "downloads.ui" - | "enterprise.deviceAttributes" - | "enterprise.hardwarePlatform" - | "enterprise.networkingAttributes" - | "enterprise.platformKeys" - | "experimental" - | "favicon" - | "fileBrowserHandler" - | "fileSystemProvider" - | "fontSettings" - | "gcm" - | "geolocation" - | "history" - | "identity" - | "identity.email" - | "idle" - | "loginState" - | "management" - | "nativeMessaging" - | "notifications" - | "offscreen" - | "pageCapture" - | "platformKeys" - | "power" - | "printerProvider" - | "printing" - | "printingMetrics" - | "privacy" - | "processes" - | "proxy" - | "readingList" - | "scripting" - | "search" - | "sessions" - | "sidePanel" - | "storage" - | "system.cpu" - | "system.display" - | "system.memory" - | "system.storage" - | "systemLog" - | "tabCapture" - | "tabGroups" - | "tabs" - | "topSites" - | "tts" - | "ttsEngine" - | "unlimitedStorage" - | "userScripts" - | "vpnProvider" - | "wallpaper" - | "webAuthenticationProxy" - | "webNavigation" - | "webRequest" - | "webRequestBlocking" - | "webRequestAuthProvider"; - + export type ManifestPermissions = | "accessibilityFeatures.modify" + | "accessibilityFeatures.read" + | "activeTab" + | "alarms" + | "audio" + | "background" + | "bookmarks" + | "browsingData" + | "certificateProvider" + | "clipboardRead" + | "clipboardWrite" + | "contentSettings" + | "contextMenus" + | "cookies" + | "debugger" + | "declarativeContent" + | "declarativeNetRequest" + | "declarativeNetRequestFeedback" + | "declarativeNetRequestWithHostAccess" + | "declarativeWebRequest" + | "desktopCapture" + | "documentScan" + | "downloads" + | "downloads.open" + | "downloads.shelf" + | "downloads.ui" + | "enterprise.deviceAttributes" + | "enterprise.hardwarePlatform" + | "enterprise.networkingAttributes" + | "enterprise.platformKeys" + | "experimental" + | "favicon" + | "fileBrowserHandler" + | "fileSystemProvider" + | "fontSettings" + | "gcm" + | "geolocation" + | "history" + | "identity" + | "identity.email" + | "idle" + | "loginState" + | "management" + | "nativeMessaging" + | "notifications" + | "offscreen" + | "pageCapture" + | "platformKeys" + | "power" + | "printerProvider" + | "printing" + | "printingMetrics" + | "privacy" + | "processes" + | "proxy" + | "readingList" + | "scripting" + | "search" + | "sessions" + | "sidePanel" + | "storage" + | "system.cpu" + | "system.display" + | "system.memory" + | "system.storage" + | "systemLog" + | "tabCapture" + | "tabGroups" + | "tabs" + | "topSites" + | "tts" + | "ttsEngine" + | "unlimitedStorage" + | "userScripts" + | "vpnProvider" + | "wallpaper" + | "webAuthenticationProxy" + | "webNavigation" + | "webRequest" + | "webRequestBlocking" + | "webRequestAuthProvider"; /** Source : https://developer.chrome.com/docs/extensions/reference/api/permissions */ export type ManifestOptionalPermissions = Exclude< - ManifestPermissions, - | "debugger" - | "declarativeNetRequest" - | "devtools" - | "experimental" - | "fontSettings" - | "geolocation" - | "proxy" - | "tts" - | "ttsEngine" - | "unlimitedStorage" - | "wallpaper" - | "webAuthenticationProxy" - >; + ManifestPermissions, + | "debugger" + | "declarativeNetRequest" + | "devtools" + | "experimental" + | "fontSettings" + | "geolocation" + | "proxy" + | "tts" + | "ttsEngine" + | "unlimitedStorage" + | "wallpaper" + | "webAuthenticationProxy" + >; export interface SearchProvider { name?: string | undefined; @@ -9085,56 +10202,51 @@ export namespace Browser { } export interface ManifestBase { - // Required + [key: string]: any; manifest_version: number; name: string; version: string; - - // Recommended default_locale?: string | undefined; description?: string | undefined; icons?: ManifestIcons | undefined; - - // Optional author?: { - email: string; - } | undefined; + email: string; + } | undefined; background_page?: string | undefined; chrome_settings_overrides?: { - homepage?: string | undefined; - search_provider?: SearchProvider | undefined; - startup_pages?: string[] | undefined; - } | undefined; + homepage?: string | undefined; + search_provider?: SearchProvider | undefined; + startup_pages?: string[] | undefined; + } | undefined; chrome_ui_overrides?: { - bookmarks_ui?: { - remove_bookmark_shortcut?: boolean | undefined; - remove_button?: boolean | undefined; + bookmarks_ui?: { + remove_bookmark_shortcut?: boolean | undefined; + remove_button?: boolean | undefined; + } | undefined; } | undefined; - } | undefined; chrome_url_overrides?: { - bookmarks?: string | undefined; - history?: string | undefined; - newtab?: string | undefined; - } | undefined; + bookmarks?: string | undefined; + history?: string | undefined; + newtab?: string | undefined; + } | undefined; commands?: { - [name: string]: { - suggested_key?: { - default?: string | undefined; - windows?: string | undefined; - mac?: string | undefined; - chromeos?: string | undefined; - linux?: string | undefined; - } | undefined; - description?: string | undefined; - global?: boolean | undefined; - }; - } | undefined; + [name: string]: { + suggested_key?: { + default?: string | undefined; + windows?: string | undefined; + mac?: string | undefined; + chromeos?: string | undefined; + linux?: string | undefined; + } | undefined; + description?: string | undefined; + global?: boolean | undefined; + }; + } | undefined; content_capabilities?: { - matches?: string[] | undefined; - permissions?: string[] | undefined; - } | undefined; - content_scripts?: - | Array<{ + matches?: string[] | undefined; + permissions?: string[] | undefined; + } | undefined; + content_scripts?: | Array<{ matches?: string[] | undefined; exclude_matches?: string[] | undefined; css?: string[] | undefined; @@ -9149,48 +10261,44 @@ export namespace Browser { converted_from_user_script?: boolean | undefined; current_locale?: string | undefined; devtools_page?: string | undefined; - event_rules?: - | Array<{ + event_rules?: | Array<{ event?: string | undefined; actions?: | Array<{ type: string; }> | undefined; - conditions?: Browser.declarativeContent.PageStateMatcherProperties[] | undefined; + conditions?: chrome.declarativeContent.PageStateMatcherProperties[] | undefined; }> | undefined; externally_connectable?: { - ids?: string[] | undefined; - matches?: string[] | undefined; - accepts_tls_channel_id?: boolean | undefined; - } | undefined; - file_browser_handlers?: - | Array<{ + ids?: string[] | undefined; + matches?: string[] | undefined; + accepts_tls_channel_id?: boolean | undefined; + } | undefined; + file_browser_handlers?: | Array<{ id?: string | undefined; default_title?: string | undefined; file_filters?: string[] | undefined; }> | undefined; file_system_provider_capabilities?: { - configurable?: boolean | undefined; - watchable?: boolean | undefined; - multiple_mounts?: boolean | undefined; - source?: string | undefined; - } | undefined; + configurable?: boolean | undefined; + watchable?: boolean | undefined; + multiple_mounts?: boolean | undefined; + source?: string | undefined; + } | undefined; homepage_url?: string | undefined; - import?: - | Array<{ + import?: | Array<{ id: string; minimum_version?: string | undefined; }> | undefined; export?: { - whitelist?: string[] | undefined; - } | undefined; + whitelist?: string[] | undefined; + } | undefined; incognito?: string | undefined; - input_components?: - | Array<{ + input_components?: | Array<{ name?: string | undefined; type?: string | undefined; id?: string | undefined; @@ -9202,83 +10310,73 @@ export namespace Browser { | undefined; key?: string | undefined; minimum_chrome_version?: string | undefined; - nacl_modules?: - | Array<{ + nacl_modules?: | Array<{ path: string; mime_type: string; }> | undefined; oauth2?: { - client_id: string; - scopes?: string[] | undefined; - } | undefined; + client_id: string; + scopes?: string[] | undefined; + } | undefined; offline_enabled?: boolean | undefined; omnibox?: { - keyword: string; - } | undefined; + keyword: string; + } | undefined; options_page?: string | undefined; options_ui?: { - page?: string | undefined; - chrome_style?: boolean | undefined; - open_in_tab?: boolean | undefined; - } | undefined; - platforms?: - | Array<{ + page?: string | undefined; + chrome_style?: boolean | undefined; + open_in_tab?: boolean | undefined; + } | undefined; + platforms?: | Array<{ nacl_arch?: string | undefined; sub_package_path: string; }> | undefined; - plugins?: - | Array<{ + plugins?: | Array<{ path: string; }> | undefined; requirements?: { - "3D"?: { - features?: string[] | undefined; - } | undefined; - plugins?: { - npapi?: boolean | undefined; + "3D"?: { + features?: string[] | undefined; + } | undefined; + plugins?: { + npapi?: boolean | undefined; + } | undefined; } | undefined; - } | undefined; sandbox?: { - pages: string[]; - content_security_policy?: string | undefined; - } | undefined; + pages: string[]; + content_security_policy?: string | undefined; + } | undefined; short_name?: string | undefined; spellcheck?: { - dictionary_language?: string | undefined; - dictionary_locale?: string | undefined; - dictionary_format?: string | undefined; - dictionary_path?: string | undefined; - } | undefined; + dictionary_language?: string | undefined; + dictionary_locale?: string | undefined; + dictionary_format?: string | undefined; + dictionary_path?: string | undefined; + } | undefined; storage?: { - managed_schema: string; - } | undefined; + managed_schema: string; + } | undefined; tts_engine?: { - voices: Array<{ - voice_name: string; - lang?: string | undefined; - gender?: string | undefined; - event_types?: string[] | undefined; - }>; - } | undefined; + voices: Array<{ + voice_name: string; + lang?: string | undefined; + gender?: string | undefined; + event_types?: string[] | undefined; + }>; + } | undefined; update_url?: string | undefined; version_name?: string | undefined; - [key: string]: any; } export interface ManifestV2 extends ManifestBase { - // Required manifest_version: 2; - - // Pick one (or none) browser_action?: ManifestAction | undefined; page_action?: ManifestAction | undefined; - - // Optional - background?: - | { + background?: | { scripts?: string[] | undefined; page?: string | undefined; persistent?: boolean | undefined; @@ -9291,19 +10389,14 @@ export namespace Browser { } export interface ManifestV3 extends ManifestBase { - // Required manifest_version: 3; - - // Optional action?: ManifestAction | undefined; - background?: - | { + background?: | { service_worker: string; type?: "module"; // If the service worker uses ES modules } | undefined; - content_scripts?: - | Array<{ + content_scripts?: | Array<{ matches?: string[] | undefined; exclude_matches?: string[] | undefined; css?: string[] | undefined; @@ -9317,9 +10410,9 @@ export namespace Browser { }> | undefined; content_security_policy?: { - extension_pages?: string; - sandbox?: string; - }; + extension_pages?: string; + sandbox?: string; + }; host_permissions?: string[] | undefined; optional_permissions?: ManifestOptionalPermissions[] | undefined; optional_host_permissions?: string[] | undefined; @@ -9328,7 +10421,6 @@ export namespace Browser { } export type Manifest = ManifestV2 | ManifestV3; - /** * Attempts to connect to connect listeners within an extension/app (such as the background page), or other extensions/apps. This is useful for content scripts connecting to their extension processes, inter-app/extension communication, and web messaging. Note that this does not connect to any listeners in a content script. Extensions may connect to content scripts embedded in tabs via tabs.connect. * @since Chrome 26 @@ -9414,9 +10506,7 @@ export namespace Browser { * Parameter status: Result of the update check. One of: "throttled", "no_update", or "update_available" * Optional parameter details: If an update is available, this contains more information about the available update. */ - export function requestUpdateCheck( - callback: (status: RequestUpdateCheckStatus, details?: UpdateCheckDetails) => void, - ): void; + export function requestUpdateCheck(callback: (status: RequestUpdateCheckStatus, details?: UpdateCheckDetails) => void): void; /** * Restart the ChromeOS device when the app runs in kiosk mode. Otherwise, it's no-op. * @since Chrome 32 @@ -9444,34 +10534,21 @@ export namespace Browser { * @since Chrome 32 * Parameter response: The JSON response object sent by the handler of the message. 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 sendMessage( - message: M, - options: MessageOptions, - responseCallback: (response: R) => void, - ): void; + export function sendMessage(message: M, options: MessageOptions, responseCallback: (response: R) => void): void; /** * Sends a single message to event listeners within your extension/app or a different extension/app. Similar to runtime.connect but only sends a single message, with an optional response. If sending to your extension, the runtime.onMessage event will be fired in each page, or runtime.onMessageExternal, if a different extension. Note that extensions cannot send messages to content scripts using this method. To send messages to content scripts, use tabs.sendMessage. * @since Chrome 26 * @param extensionId The ID of the extension/app to send the message to. If omitted, the message will be sent to your own extension/app. Required if sending messages from a web page for web messaging. * Parameter response: The JSON response object sent by the handler of the message. 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 sendMessage( - extensionId: string | undefined | null, - message: M, - responseCallback: (response: R) => void, - ): void; + export function sendMessage(extensionId: string | undefined | null, message: M, responseCallback: (response: R) => void): void; /** * Sends a single message to event listeners within your extension/app or a different extension/app. Similar to runtime.connect but only sends a single message, with an optional response. If sending to your extension, the runtime.onMessage event will be fired in each page, or runtime.onMessageExternal, if a different extension. Note that extensions cannot send messages to content scripts using this method. To send messages to content scripts, use tabs.sendMessage. * @since Chrome 32 * @param extensionId The ID of the extension/app to send the message to. If omitted, the message will be sent to your own extension/app. Required if sending messages from a web page for web messaging. * Parameter response: The JSON response object sent by the handler of the message. 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 sendMessage( - extensionId: string | undefined | null, - message: Message, - options: MessageOptions, - responseCallback: (response: Response) => void, - ): void; + export function sendMessage(extensionId: string | undefined | null, message: Message, options: MessageOptions, responseCallback: (response: Response) => void): void; /** * Sends a single message to event listeners within your extension/app or a different extension/app. Similar to runtime.connect but only sends a single message, with an optional response. If sending to your extension, the runtime.onMessage event will be fired in each page, or runtime.onMessageExternal, if a different extension. Note that extensions cannot send messages to content scripts using this method. To send messages to content scripts, use tabs.sendMessage. * @since Chrome 26 @@ -9481,10 +10558,7 @@ export namespace Browser { * Sends a single message to event listeners within your extension/app or a different extension/app. Similar to runtime.connect but only sends a single message, with an optional response. If sending to your extension, the runtime.onMessage event will be fired in each page, or runtime.onMessageExternal, if a different extension. Note that extensions cannot send messages to content scripts using this method. To send messages to content scripts, use tabs.sendMessage. * @since Chrome 32 */ - export function sendMessage( - message: M, - options: MessageOptions, - ): Promise; + export function sendMessage(message: M, options: MessageOptions): Promise; /** * Sends a single message to event listeners within your extension/app or a different extension/app. Similar to runtime.connect but only sends a single message, with an optional response. If sending to your extension, the runtime.onMessage event will be fired in each page, or runtime.onMessageExternal, if a different extension. Note that extensions cannot send messages to content scripts using this method. To send messages to content scripts, use tabs.sendMessage. * @since Chrome 26 @@ -9496,11 +10570,7 @@ export namespace Browser { * @since Chrome 32 * @param extensionId The ID of the extension/app to send the message to. If omitted, the message will be sent to your own extension/app. Required if sending messages from a web page for web messaging. */ - export function sendMessage( - extensionId: string | undefined | null, - message: Message, - options: MessageOptions, - ): Promise; + export function sendMessage(extensionId: string | undefined | null, message: Message, options: MessageOptions): Promise; /** * Send a single message to a native application. * @since Chrome 28 @@ -9508,21 +10578,14 @@ export namespace Browser { * @param message The message that will be passed to the native messaging host. * Parameter response: The response message sent by the native messaging host. If an error occurs while connecting to the native messaging host, the callback will be called with no arguments and runtime.lastError will be set to the error message. */ - export function sendNativeMessage( - application: string, - message: object, - responseCallback: (response: any) => void, - ): void; + export function sendNativeMessage(application: string, message: object, responseCallback: (response: any) => void): void; /** * Send a single message to a native application. * @since Chrome 28 * @param application The of the native messaging host. * @param message The message that will be passed to the native messaging host. */ - export function sendNativeMessage( - application: string, - message: object, - ): Promise; + export function sendNativeMessage(application: string, message: object): Promise; /** * Sets the URL to be visited upon uninstallation. This may be used to clean up server-side data, do analytics, and implement surveys. Maximum 255 characters. * @since Chrome 41 @@ -9545,7 +10608,6 @@ export namespace Browser { * @since Chrome 42 */ export function openOptionsPage(callback?: () => void): void; - /** * Fired when a connection is made from either an extension process or a content script. * @since Chrome 26 @@ -9583,112 +10645,225 @@ export namespace Browser { */ export var onRestartRequired: RuntimeRestartRequiredEvent; /** - * Fired when an update is available, but isn't installed immediately because the app is currently running. If you do nothing, the update will be installed the next time the background page gets unloaded, if you want it to be installed sooner you can explicitly call Browser.runtime.reload(). If your extension is using a persistent background page, the background page of course never gets unloaded, so unless you call Browser.runtime.reload() manually in response to this event the update will not get installed until the next time chrome itself restarts. If no handlers are listening for this event, and your extension has a persistent background page, it behaves as if Browser.runtime.reload() is called in response to this event. + * Fired when an update is available, but isn't installed immediately because the app is currently running. If you do nothing, the update will be installed the next time the background page gets unloaded, if you want it to be installed sooner you can explicitly call chrome.runtime.reload(). If your extension is using a persistent background page, the background page of course never gets unloaded, so unless you call chrome.runtime.reload() manually in response to this event the update will not get installed until the next time chrome itself restarts. If no handlers are listening for this event, and your extension has a persistent background page, it behaves as if chrome.runtime.reload() is called in response to this event. * @since Chrome 25 */ export var onUpdateAvailable: RuntimeUpdateAvailableEvent; /** - * @deprecated since Chrome 33. Please use Browser.runtime.onRestartRequired. + * @deprecated since Chrome 33. Please use chrome.runtime.onRestartRequired. * Fired when a Chrome update is available, but isn't installed immediately because a browser restart is required. */ export var onBrowserUpdateAvailable: RuntimeEvent; - /** * @since chrome 115+ * @requires MV3+ * Listens for connections made from user scripts associated with this extension. */ export var onUserScriptConnect: ExtensionConnectEvent; - /** * @since chrome 115+ * @requires MV3+ * Listens for messages sent from user scripts associated with this extension. */ export var onUserScriptMessage: ExtensionMessageEvent; - } - //////////////////// - // Scripting - //////////////////// - /** - * Use the `Browser.scripting` API to execute script in different contexts. - * - * Permissions: "scripting" - * @since Chrome 88, MV3 - */ - export namespace scripting { - /* The CSS style origin for a style change. */ - export type StyleOrigin = "AUTHOR" | "USER"; + /** An object containing information about the current browser. */ + interface BrowserInfo { + /** The name of the browser, for example 'Firefox'. */ + name: string; + /** The name of the browser vendor, for example 'Mozilla'. */ + vendor: string; + /** The browser's version, for example '42.0.0' or '0.8.1pre'. */ + version: string; + /** The browser's build ID/date, for example '20160101'. */ + buildID: string; + } - /* The JavaScript world for a script to execute within. */ - export type ExecutionWorld = "ISOLATED" | "MAIN"; + /** This will be defined during an API method callback if there was an error */ + interface _LastError { + /** Details about the error which occurred. */ + message?: string | undefined; + } - export interface InjectionResult { + /** If an update is available, this contains more information about the available update. */ + interface _RequestUpdateCheckReturnDetails { + /** The version of the available update. */ + version: string; + } + + interface _ConnectConnectInfo { + /** Will be passed into onConnect for processes that are listening for the connection event. */ + name?: string | undefined; /** - * The document associated with the injection. - * @since Chrome 106 + * Whether the TLS channel ID will be passed into onConnectExternal for processes that are listening for the connection event. */ - documentId: string; + includeTlsChannelId?: boolean | undefined; + } + + interface _SendMessageOptions { /** - * The frame associated with the injection. - * @since Chrome 90 + * Whether the TLS channel ID will be passed into onMessageExternal for processes that are listening for the connection event. + * @deprecated Unsupported on Firefox at this time. */ - frameId: number; - /* The result of the script execution. */ - result?: T | undefined; + includeTlsChannelId?: boolean | undefined; } - export interface InjectionTarget { - /* Whether the script should inject into all frames within the tab. Defaults to false. This must not be true if frameIds is specified. */ - allFrames?: boolean | undefined; + interface _OnInstalledDetails { + /** The reason that this event is being dispatched. */ + reason: OnInstalledReason; /** - * The IDs of specific documentIds to inject into. This must not be set if frameIds is set. - * @since Chrome 106 + * Indicates the previous version of the extension, which has just been updated. This is present only if 'reason' is 'update'. */ - documentIds?: string[] | undefined; - /* The IDs of specific frames to inject into. */ - frameIds?: number[] | undefined; - /* The ID of the tab into which to inject. */ - tabId: number; + previousVersion?: string | undefined; + /** Indicates whether the addon is installed as a temporary extension. */ + temporary: boolean; + /** + * Indicates the ID of the imported shared module extension which updated. This is present only if 'reason' is 'shared_module_update'. + * @deprecated Unsupported on Firefox at this time. + */ + id?: string | undefined; } - export interface CSSInjection { - /* A string containing the CSS to inject. Exactly one of files and css must be specified. */ - css?: string | undefined; - /* The path of the CSS files to inject, relative to the extension's root directory. NOTE: Currently a maximum of one file is supported. Exactly one of files and css must be specified. */ - files?: string[] | undefined; - /* The style origin for the injection. Defaults to 'AUTHOR'. */ - origin?: StyleOrigin | undefined; - /* Details specifying the target into which to insert the CSS. */ - target: InjectionTarget; + /** The manifest details of the available update. */ + interface _OnUpdateAvailableDetails { + /** The version number of the available update. */ + version: string; } - export type ScriptInjection = - & { - /* Details specifying the target into which to inject the script. */ - target: InjectionTarget; - /* The JavaScript world for a script to execute within. */ - world?: ExecutionWorld; - /* Whether the injection should be triggered in the target as soon as possible. Note that this is not a guarantee that injection will occur prior to page load, as the page may have already loaded by the time the script reaches the target. */ - injectImmediately?: boolean; - } - & ( - | { - /* The path of the JS files to inject, relative to the extension's root directory. NOTE: Currently a maximum of one file is supported. Exactly one of files and function must be specified. */ - files: string[]; - } - | ({ - /* A JavaScript function to inject. This function will be serialized, and then deserialized for injection. This means that any bound parameters and execution context will be lost. Exactly one of files and function must be specified. */ - func: () => Result; - } | { - /* A JavaScript function to inject. This function will be serialized, and then deserialized for injection. This means that any bound parameters and execution context will be lost. Exactly one of files and function must be specified. */ - func: (...args: Args) => Result; - /* The arguments to carry into a provided function. This is only valid if the func parameter is specified. These arguments must be JSON-serializable. */ - args: Args; - }) - ); + /** + * Get the frameId of any window global or frame element. + * @param target A WindowProxy or a Browsing Context container element (IFrame, Frame, Embed, Object) for the target frame. + * @returns The frameId of the target frame, or -1 if it doesn't exist. + */ + function getFrameId(target: any): number; + /** Returns information about the current browser. */ + function getBrowserInfo(): Promise; + + /** This will be defined during an API method callback if there was an error */ + const lastError: _LastError | undefined; + /** The ID of the extension/app. */ + const id: string; + /** + * Fired when a profile that has this extension installed first starts up. This event is not fired for incognito profiles. + */ + const onStartup: WebExtEvent<() => void>; + /** + * Fired when the extension is first installed, when the extension is updated to a new version, and when the browser is updated to a new version. + */ + const onInstalled: WebExtEvent<(details: _OnInstalledDetails) => void>; + /** + * Sent to the event page just before it is unloaded. This gives the extension opportunity to do some clean up. Note that since the page is unloading, any asynchronous operations started while handling this event are not guaranteed to complete. If more activity for the event page occurs before it gets unloaded the onSuspendCanceled event will be sent and the page won't be unloaded. + */ + const onSuspend: WebExtEvent<() => void>; + /** Sent after onSuspend to indicate that the app won't be unloaded after all. */ + const onSuspendCanceled: WebExtEvent<() => void>; + /** + * Fired when an update is available, but isn't installed immediately because the app is currently running. If you do nothing, the update will be installed the next time the background page gets unloaded, if you want it to be installed sooner you can explicitly call `runtime.reload`. If your extension is using a persistent background page, the background page of course never gets unloaded, so unless you call `runtime.reload` manually in response to this event the update will not get installed until the next time the browser itself restarts. If no handlers are listening for this event, and your extension has a persistent background page, it behaves as if `runtime.reload` is called in response to this event. + * @param details The manifest details of the available update. + */ + const onUpdateAvailable: WebExtEvent<(details: _OnUpdateAvailableDetails) => void>; + /** + * Fired when an update for the browser is available, but isn't installed immediately because a browser restart is required. + * @deprecated Please use `runtime.onRestartRequired`. + */ + const onBrowserUpdateAvailable: WebExtEvent<() => void> | undefined; + /** Fired when a connection is made from either an extension process or a content script. */ + const onConnect: WebExtEvent<(port: Port) => void>; + /** Fired when a connection is made from another extension. */ + const onConnectExternal: WebExtEvent<(port: Port) => void>; + /** + * Fired when a message is sent from either an extension process or a content script. + * @param message The message sent by the calling script. + * @param sendResponse Function to call (at most once) when you have a response. The argument should be any JSON-ifiable object. If you have more than one `onMessage` listener in the same document, then only one may send a response. This function becomes invalid when the event listener returns, unless you return true from the event listener to indicate you wish to send a response asynchronously (this will keep the message channel open to the other end until `sendResponse` is called). + * @returns Return true from the event listener if you wish to call `sendResponse` after the event listener returns. + */ + const onMessage: WebExtEvent< + // eslint-disable-next-line @typescript-eslint/no-invalid-void-type + (message: any, sender: MessageSender, sendResponse: (response?: any) => void) => boolean | Promise | void + >; + /** + * Fired when a message is sent from another extension/app. Cannot be used in a content script. + * @param message The message sent by the calling script. + * @param sendResponse Function to call (at most once) when you have a response. The argument should be any JSON-ifiable object. If you have more than one `onMessage` listener in the same document, then only one may send a response. This function becomes invalid when the event listener returns, unless you return true from the event listener to indicate you wish to send a response asynchronously (this will keep the message channel open to the other end until `sendResponse` is called). + * @returns Return true from the event listener if you wish to call `sendResponse` after the event listener returns. + */ + const onMessageExternal: WebExtEvent< + // eslint-disable-next-line @typescript-eslint/no-invalid-void-type + (message: any, sender: MessageSender, sendResponse: (response?: any) => void) => boolean | Promise | void + >; + /** + * Fired when an app or the device that it runs on needs to be restarted. The app should close all its windows at its earliest convenient time to let the restart to happen. If the app does nothing, a restart will be enforced after a 24-hour grace period has passed. Currently, this event is only fired for Chrome OS kiosk apps. + * @param reason The reason that the event is being dispatched. + * @deprecated Unsupported on Firefox at this time. + */ + const onRestartRequired: WebExtEvent<(reason: OnRestartRequiredReason) => void> | undefined; + } + + /** + * Use the `chrome.scripting` API to execute script in different contexts. + * + * Permissions: "scripting" + * @since Chrome 88, MV3 + */ + export namespace scripting { + export type StyleOrigin = "AUTHOR" | "USER"; + export type ExecutionWorld = "ISOLATED" | "MAIN"; + + export interface InjectionResult { + /** + * The document associated with the injection. + * @since Chrome 106 + */ + documentId: string; + /** + * The frame associated with the injection. + * @since Chrome 90 + */ + frameId: number; + result?: T | undefined; + } + + export interface InjectionTarget { + allFrames?: boolean | undefined; + /** + * The IDs of specific documentIds to inject into. This must not be set if frameIds is set. + * @since Chrome 106 + */ + documentIds?: string[] | undefined; + frameIds?: number[] | undefined; + tabId: number; + } + + export interface CSSInjection { + css?: string | undefined; + files?: string[] | undefined; + origin?: StyleOrigin | undefined; + target: InjectionTarget; + } + export type ScriptInjection = & { + /* Details specifying the target into which to inject the script. */ + target: InjectionTarget; + /* The JavaScript world for a script to execute within. */ + world?: ExecutionWorld; + /* Whether the injection should be triggered in the target as soon as possible. Note that this is not a guarantee that injection will occur prior to page load, as the page may have already loaded by the time the script reaches the target. */ + injectImmediately?: boolean; + } + & ( + | { + /* The path of the JS files to inject, relative to the extension's root directory. NOTE: Currently a maximum of one file is supported. Exactly one of files and function must be specified. */ + files: string[]; + } + | ({ + /* A JavaScript function to inject. This function will be serialized, and then deserialized for injection. This means that any bound parameters and execution context will be lost. Exactly one of files and function must be specified. */ + func: () => Result; + } | { + /* A JavaScript function to inject. This function will be serialized, and then deserialized for injection. This means that any bound parameters and execution context will be lost. Exactly one of files and function must be specified. */ + func: (...args: Args) => Result; + /* The arguments to carry into a provided function. This is only valid if the func parameter is specified. These arguments must be JSON-serializable. */ + args: Args; + }) + ); type Awaited = T extends PromiseLike ? U : T; interface RegisteredContentScript { @@ -9700,7 +10875,7 @@ export namespace Browser { js?: string[]; matches?: string[]; persistAcrossSessions?: boolean; - runAt?: "document_start" | "document_end" | "document_idle"; + runAt?: extensionTypes.RunAt; world?: ExecutionWorld; } @@ -9718,10 +10893,7 @@ export namespace Browser { * The details of the script which to inject. * @return The `executeScript` method provides its result via callback or returned as a `Promise` (MV3 only). The resulting array contains the result of execution for each frame where the injection succeeded. */ - export function executeScript( - injection: ScriptInjection, - ): Promise>>>; - + export function executeScript(injection: ScriptInjection): Promise>>>; /** * Injects a script into a target context. The script will be run at document_end. * @param injection @@ -9729,11 +10901,7 @@ export namespace Browser { * @param callback * Invoked upon completion of the injection. The resulting array contains the result of execution for each frame where the injection succeeded. */ - export function executeScript( - injection: ScriptInjection, - callback: (results: Array>>) => void, - ): void; - + export function executeScript(injection: ScriptInjection, callback: (results: Array>>) => void): void; /** * Inserts a CSS stylesheet into a target context. If multiple frames are specified, unsuccessful injections are ignored. * @param injection @@ -9741,7 +10909,6 @@ export namespace Browser { * @return The `insertCSS` method provides its result via callback or returned as a `Promise` (MV3 only). It has no parameters. */ export function insertCSS(injection: CSSInjection): Promise; - /** * Inserts a CSS stylesheet into a target context. If multiple frames are specified, unsuccessful injections are ignored. * @param injection @@ -9750,7 +10917,6 @@ export namespace Browser { * Invoked upon completion of the injection. */ export function insertCSS(injection: CSSInjection, callback: () => void): void; - /** * Removes a CSS stylesheet that was previously inserted by this extension from a target context. * @param injection @@ -9761,7 +10927,6 @@ export namespace Browser { * @since Chrome 90 */ export function removeCSS(injection: CSSInjection): Promise; - /** * Removes a CSS stylesheet that was previously inserted by this extension from a target context. * @param injection @@ -9773,27 +10938,23 @@ export namespace Browser { * @since Chrome 90 */ export function removeCSS(injection: CSSInjection, callback: () => void): void; - /** * Registers one or more content scripts. * @param scripts */ export function registerContentScripts(scripts: RegisteredContentScript[]): Promise; - /** * Registers one or more content scripts. * @param scripts * @param callback */ export function registerContentScripts(scripts: RegisteredContentScript[], callback: () => void): void; - /** * Unregister one or more content scripts. * @param filter * @param callback */ export function unregisterContentScripts(filter?: ContentScriptFilter): Promise; - /** * Unregister one or more content scripts. * @param filter @@ -9801,14 +10962,12 @@ export namespace Browser { */ export function unregisterContentScripts(callback: () => void): void; export function unregisterContentScripts(filter: ContentScriptFilter, callback: () => void): void; - /** * Returns all the content scripts registered with scripting.registerContentScripts() * or a subset of the registered scripts when using a filter. * @param filter */ export function getRegisteredContentScripts(filter?: ContentScriptFilter): Promise; - /** * Returns all the content scripts registered with scripting.registerContentScripts() * or a subset of the registered scripts when using a filter. @@ -9816,30 +10975,74 @@ export namespace Browser { * @param callback */ export function getRegisteredContentScripts(callback: (scripts: RegisteredContentScript[]) => void): void; - export function getRegisteredContentScripts( - filter: ContentScriptFilter, - callback: (scripts: RegisteredContentScript[]) => void, - ): void; - + export function getRegisteredContentScripts(filter: ContentScriptFilter, callback: (scripts: RegisteredContentScript[]) => void): void; /** * Updates one or more content scripts. * @param scripts */ export function updateContentScripts(scripts: RegisteredContentScript[]): Promise; - /** * Updates one or more content scripts. * @param scripts * @param callback */ export function updateContentScripts(scripts: RegisteredContentScript[], callback: () => void): void; + + /** Details of a script injection */ + interface ScriptInjection { + /** + * The arguments to curry into a provided function. This is only valid if the `func` parameter is specified. These arguments must be JSON-serializable. + */ + args?: any[] | undefined; + /** + * The path of the JS files to inject, relative to the extension's root directory. Exactly one of `files` and `func` must be specified. + */ + files?: string[] | undefined; + /** + * A JavaScript function to inject. This function will be serialized, and then deserialized for injection. This means that any bound parameters and execution context will be lost. Exactly one of `files` and `func` must be specified. + */ + func?: () => void | undefined; + /** Details specifying the target into which to inject the script. */ + target: InjectionTarget; + world?: ExecutionWorld | undefined; + /** + * Whether the injection should be triggered in the target as soon as possible (but not necessarily prior to page load). + */ + injectImmediately?: boolean | undefined; + } + + interface _UpdateContentScriptsScripts { + /** Specifies if this content script will persist into future sessions. */ + persistAcrossSessions?: boolean | undefined; + /** + * If specified true, it will inject into all frames, even if the frame is not the top-most frame in the tab. Each frame is checked independently for URL requirements; it will not inject into child frames if the URL requirements are not met. Defaults to false, meaning that only the top frame is matched. + */ + allFrames?: boolean | undefined; + /** Excludes pages that this content script would otherwise be injected into. */ + excludeMatches?: string[] | undefined; + /** The id of the content script, specified in the API call. */ + id: string; + /** + * The list of JavaScript files to be injected into matching pages. These are injected in the order they appear in this array. + */ + js?: _manifest.ExtensionURL[] | undefined; + /** + * Specifies which pages this content script will be injected into. Must be specified for `registerContentScripts()`. + */ + matches?: string[] | undefined; + /** + * Specifies when JavaScript files are injected into the web page. The preferred and default value is `document_idle`. + */ + runAt?: extensionTypes.RunAt | undefined; + /** + * The list of CSS files to be injected into matching pages. These are injected in the order they appear in this array. + */ + css?: _manifest.ExtensionURL[] | undefined; + } } - //////////////////// - // Sessions - //////////////////// /** - * Use the `Browser.sessions` API to query and restore tabs and windows from a browsing session. + * Use the `chrome.sessions` API to query and restore tabs and windows from a browsing session. * * Permissions: "sessions" */ @@ -9874,11 +11077,11 @@ export namespace Browser { sessions: Session[]; } - export interface SessionChangedEvent extends Browser.events.Event<() => void> {} + export interface SessionChangedEvent extends chrome.events.Event<() => void> { + } /** The maximum number of sessions.Session that will be included in a requested list. */ export var MAX_SESSION_RESULTS: number; - /** * 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). @@ -9934,26 +11137,86 @@ export namespace Browser { * Parameter restoredSession: A sessions.Session containing the restored windows.Window or tabs.Tab object. */ export function restore(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; + + /** + * Forget a recently closed tab. + * @param windowId The windowId of the window to which the recently closed tab to be forgotten belongs. + * @param sessionId The sessionId (closedId) of the recently closed tab to be forgotten. + */ + function forgetClosedTab(windowId: number, sessionId: string): Promise; + /** + * Forget a recently closed window. + * @param sessionId The sessionId (closedId) of the recently closed window to be forgotten. + */ + function forgetClosedWindow(sessionId: string): Promise; + /** + * Set a key/value pair on a given tab. + * @param tabId The id of the tab that the key/value pair is being set on. + * @param key The key which corresponds to the value being set. + * @param value The value being set. + */ + function setTabValue(tabId: number, key: string, value: any): Promise; + /** + * Retrieve a value that was set for a given key on a given tab. + * @param tabId The id of the tab whose value is being retrieved from. + * @param key The key which corresponds to the value. + */ + function getTabValue(tabId: number, key: string): Promise; + /** + * Remove a key/value pair that was set on a given tab. + * @param tabId The id of the tab whose key/value pair is being removed. + * @param key The key which corresponds to the value. + */ + function removeTabValue(tabId: number, key: string): Promise; + /** + * Set a key/value pair on a given window. + * @param windowId The id of the window that the key/value pair is being set on. + * @param key The key which corresponds to the value being set. + * @param value The value being set. + */ + function setWindowValue(windowId: number, key: string, value: any): Promise; + /** + * Retrieve a value that was set for a given key on a given window. + * @param windowId The id of the window whose value is being retrieved from. + * @param key The key which corresponds to the value. + */ + function getWindowValue(windowId: number, key: string): Promise; + /** + * Remove a key/value pair that was set on a given window. + * @param windowId The id of the window whose key/value pair is being removed. + * @param key The key which corresponds to the value. + */ + function removeWindowValue(windowId: number, key: string): Promise; + + /** The maximum number of `sessions.Session` that will be included in a requested list. */ + const MAX_SESSION_RESULTS: number; + /** + * Fired when recently closed tabs and/or windows are changed. This event does not monitor synced sessions changes. + */ + const onChanged: WebExtEvent<() => void>; } - //////////////////// - // Storage - //////////////////// /** - * Use the `Browser.storage` API to store, retrieve, and track changes to user data. + * Use the `chrome.storage` API to store, retrieve, and track changes to user data. * * Permissions: "storage" */ export namespace storage { /** NoInfer for old TypeScript versions */ type NoInferX = T[][T extends any ? 0 : never]; - // The next line prevents things without the export keyword from being automatically exported (like NoInferX) - export {}; + export { }; export interface StorageArea { + /** + * 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; /** * 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. @@ -9967,10 +11230,7 @@ export namespace Browser { * @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( - keys: keyof T | Array | null, - callback: (bytesInUse: number) => void, - ): void; + getBytesInUse(keys: keyof T | Array | null, 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). @@ -10027,9 +11287,7 @@ export namespace Browser { * @return A Promise that resolves with an object containing items * @since MV3 */ - get( - keys?: NoInferX | Array> | Partial> | null, - ): Promise; + 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. @@ -10037,10 +11295,7 @@ export namespace Browser { * @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, - callback: (items: T) => void, - ): void; + get(keys: NoInferX | Array> | Partial> | null, 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). @@ -10061,14 +11316,6 @@ export namespace Browser { * @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; /** * Gets all keys from storage. * @return A Promise that resolves with an array of keys. @@ -10123,50 +11370,92 @@ export namespace Browser { QUOTA_BYTES: number; } - export interface StorageAreaChangedEvent - extends Browser.events.Event<(changes: { [key: string]: StorageChange }) => void> - {} + export interface StorageAreaChangedEvent extends chrome.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 AreaName = keyof Pick; - export type AccessLevel = keyof typeof AccessLevel; + export interface StorageChangedEvent extends chrome.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"; - }; - + 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; - /** * 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. * @since Chrome 102 */ export var session: SessionStorageArea; - /** Fired when one or more items change. */ export var onChanged: StorageChangedEvent; + + interface StorageAreaSync { + /** + * Fired when one or more items change. + * @param changes Object mapping each key that changed to its corresponding `storage.StorageChange` for that item. + */ + onChanged: WebExtEvent<(changes: { [key: string]: StorageChange }) => 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 (see description of the object). An empty list or object will return an empty result object. Pass in `null` to get the entire contents of storage. + */ + get(keys?: null | string | string[] | { [key: string]: any }): Promise<{ [key: string]: any }>; + /** + * Gets the amount of space (in bytes) being used by one or more items. + * @param [keys] A single key or list of keys to get the total usage for. An empty list will return 0\. Pass in `null` to get the total usage of all of storage. + */ + getBytesInUse(keys?: null | string | string[]): Promise; + /** + * Sets multiple items. + * @param items An object which gives each key/value pair to update storage with. Any other key/value pairs in storage will not be affected. + * + * Primitive values such as numbers will serialize as expected. Values with a `typeof` `"object"` and `"function"` will typically serialize to `{}`, with the exception of `Array` (serializes as expected), `Date`, and `Regex` (serialize using their `String` representation). + */ + set(items: { [key: string]: any }): Promise; + /** + * Removes one or more items from storage. + * @param keys A single key or a list of keys for items to remove. + */ + remove(keys: string | string[]): Promise; + /** Removes all items from storage. */ + clear(): Promise; + } + + /** Items in the `sync` storage area are synced by the browser. */ + const sync: StorageAreaSync; + /** Items in the `local` storage area are local to each machine. */ + const local: StorageArea; + /** + * Items in the `managed` storage area are set by administrators or native applications, and are read-only for the extension; trying to modify this namespace results in an error. + */ + const managed: StorageArea; + /** + * Items in the `session` storage area are kept in memory, and only until the either browser or extension is closed or reloaded. + * + * Not allowed in: Content scripts + */ + const session: StorageArea; + /** + * Fired when one or more items change. + * @param changes Object mapping each key that changed to its corresponding `storage.StorageChange` for that item. + * @param areaName The name of the storage area (`"sync"`, `"local"` or `"managed"`) the changes are for. + */ + const onChanged: WebExtEvent<(changes: { [key: string]: StorageChange }, areaName: string) => void>; } - //////////////////// - // Socket - //////////////////// - /** - * @deprecated Part of the deprecated Chrome Apps platform - */ + /** @deprecated Part of the deprecated Chrome Apps platform */ export namespace socket { export interface CreateInfo { socketId: number; @@ -10207,56 +11496,23 @@ export namespace Browser { address: string; } - export function create( - type: string, - options?: { [key: string]: unknown }, - callback?: (createInfo: CreateInfo) => void, - ): void; + export function create(type: string, options?: { [key: string]: unknown }, callback?: (createInfo: CreateInfo) => void): void; export function destroy(socketId: number): void; - export function connect( - socketId: number, - hostname: string, - port: number, - callback: (result: number) => void, - ): void; + export function connect(socketId: number, hostname: string, port: number, callback: (result: number) => void): void; export function bind(socketId: number, address: string, port: number, callback: (result: number) => void): void; export function disconnect(socketId: number): void; export function read(socketId: number, bufferSize?: number, callback?: (readInfo: ReadInfo) => void): void; export function write(socketId: number, data: ArrayBuffer, callback?: (writeInfo: WriteInfo) => void): void; - export function recvFrom( - socketId: number, - bufferSize?: number, - callback?: (recvFromInfo: RecvFromInfo) => void, - ): void; - export function sendTo( - socketId: number, - data: ArrayBuffer, - address: string, - port: number, - callback?: (writeInfo: WriteInfo) => void, - ): void; - export function listen( - socketId: number, - address: string, - port: number, - backlog?: number, - callback?: (result: number) => void, - ): void; + export function recvFrom(socketId: number, bufferSize?: number, callback?: (recvFromInfo: RecvFromInfo) => void): void; + export function sendTo(socketId: number, data: ArrayBuffer, address: string, port: number, callback?: (writeInfo: WriteInfo) => void): void; + export function listen(socketId: number, address: string, port: number, backlog?: number, callback?: (result: number) => void): void; export function accept(socketId: number, callback?: (acceptInfo: AcceptInfo) => void): void; - export function setKeepAlive( - socketId: number, - enable: boolean, - delay?: number, - callback?: (result: boolean) => void, - ): void; + export function setKeepAlive(socketId: number, enable: boolean, delay?: number, callback?: (result: boolean) => void): void; export function setNoDelay(socketId: number, noDelay: boolean, callback?: (result: boolean) => void): void; export function getInfo(socketId: number, callback: (result: SocketInfo) => void): void; export function getNetworkList(callback: (result: NetworkInterface[]) => void): void; } - //////////////////// - // System CPU - //////////////////// /** * Use the `system.cpu` API to query CPU metadata. * @@ -10297,7 +11553,6 @@ export namespace Browser { /** 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). @@ -10305,11 +11560,8 @@ export namespace Browser { export function getInfo(): Promise; } - //////////////////// - // System Memory - //////////////////// /** - * The `Browser.system.memory` API. + * The `chrome.system.memory` API. * * Permissions: "system.memory" */ @@ -10323,7 +11575,6 @@ export namespace Browser { /** 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). @@ -10331,11 +11582,8 @@ export namespace Browser { export function getInfo(): Promise; } - //////////////////// - // System Storage - //////////////////// /** - * Use the `Browser.system.storage` API to query storage device information and be notified when a removable storage device is attached and detached. + * Use the `chrome.system.storage` API to query storage device information and be notified when a removable storage device is attached and detached. * * Permissions: "system.storage" */ @@ -10363,9 +11611,11 @@ export namespace Browser { availableCapacity: number; } - export interface SystemStorageAttachedEvent extends Browser.events.Event<(info: StorageUnitInfo) => void> {} + export interface SystemStorageAttachedEvent extends chrome.events.Event<(info: StorageUnitInfo) => void> { + } - export interface SystemStorageDetachedEvent extends Browser.events.Event<(id: string) => void> {} + export interface SystemStorageDetachedEvent extends chrome.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; @@ -10398,16 +11648,12 @@ export namespace Browser { * @return The `getAvailableCapacity` method provides its result via callback or returned as a `Promise` (MV3 only). */ export function getAvailableCapacity(id: string): Promise; - /** Fired when a new removable storage is attached to the system. */ export var onAttached: SystemStorageAttachedEvent; /** Fired when a removable storage is detached from the system. */ export var onDetached: SystemStorageDetachedEvent; } - //////////////////// - // System Display // - //////////////////// /** * Use the `system.display` API to query display metadata. * @@ -10418,7 +11664,7 @@ export namespace Browser { TOP = "top", RIGHT = "right", BOTTOM = "bottom", - LEFT = "left", + LEFT = "left" } /** @@ -10434,7 +11680,7 @@ export namespace Browser { * Specifies that the specified source display will be mirrored to the provided destination displays. * All other connected displays will be extended. */ - MIXED = "mixed", + MIXED = "mixed" } export interface Bounds { @@ -10623,7 +11869,7 @@ export namespace Browser { */ export enum ActiveState { ACTIVE = "active", - INACTIVE = "inactive", + INACTIVE = "inactive" } export interface DisplayUnitInfo { @@ -10670,7 +11916,8 @@ export namespace Browser { dpiX: number; /** The number of pixels per inch along the y-axis. */ dpiY: number; - /** The display's clockwise rotation in degrees relative to the vertical position. + /** + * The display's clockwise rotation in degrees relative to the vertical position. * Currently exposed only on ChromeOS. Will be set to 0 on other platforms. * A value of -1 will be interpreted as auto-rotate when the device is in a physical tablet state. * @platform ChromeOS only @@ -10748,7 +11995,6 @@ export namespace Browser { export function getInfo(flags: GetInfoFlags, callback: (displayInfo: DisplayUnitInfo[]) => void): void; export function getInfo(): Promise; export function getInfo(flags: GetInfoFlags): Promise; - /** * Requests the layout info for all displays * Can return its result via Promise in Manifest V3 or later since Chrome 91. @@ -10757,7 +12003,6 @@ export namespace Browser { */ export function getDisplayLayout(callback: (layouts: DisplayLayout[]) => void): void; export function getDisplayLayout(): Promise; - /** * requires(CrOS Kiosk apps | WebUI) This is only available to Chrome OS Kiosk apps and Web UI. * @description @@ -10770,7 +12015,6 @@ export namespace Browser { */ export function setDisplayProperties(id: string, info: DisplayProperties, callback: () => void): void; export function setDisplayProperties(id: string, info: DisplayProperties): Promise; - /** * Set the layout for all displays. * Any display not included will use the default layout. @@ -10783,7 +12027,6 @@ export namespace Browser { */ export function setDisplayLayout(layouts: DisplayLayout[], callback: () => void): void; export function setDisplayLayout(layouts: DisplayLayout[]): Promise; - /** * Enables/disables the unified desktop feature. * If enabled while mirroring is active, the desktop mode will not change until mirroring is turned off. @@ -10793,7 +12036,6 @@ export namespace Browser { * @param enabled True if unified desktop should be enabled. */ export function enableUnifiedDesktop(enabled: boolean): void; - /** * Starts overscan calibration for a display. * This will show an overlay on the screen indicating the current overscan insets. @@ -10802,7 +12044,6 @@ export namespace Browser { * @param id The display's unique identifier. */ export function overscanCalibrationStart(id: string): void; - /** * Adjusts the current overscan insets for a display. * Typically this should either move the display along an axis (e.g. left+right have the same value) @@ -10813,21 +12054,18 @@ export namespace Browser { * @param delta The amount to change the overscan insets. */ export function overscanCalibrationAdjust(id: string, delta: Insets): void; - /** * Resets the overscan insets for a display to the last saved value (i.e before Start was called). * @since Chrome 53 * @param id The display's unique identifier. */ export function overscanCalibrationReset(id: string): void; - /** * Complete overscan adjustments for a display by saving the current values and hiding the overlay. * @since Chrome 53 * @param id The display's unique identifier. */ export function overscanCalibrationComplete(id: string): void; - /** * Displays the native touch calibration UX for the display with `id` as display id. * This will show an overlay on the screen with required instructions on how to proceed. @@ -10839,7 +12077,6 @@ export namespace Browser { */ export function showNativeTouchCalibration(id: string, callback: (success: boolean) => void): void; export function showNativeTouchCalibration(id: string): Promise; - /** * Starts custom touch calibration for a display. * This should be called when using a custom UX for collecting calibration data. @@ -10848,7 +12085,6 @@ export namespace Browser { * @param id The display's unique identifier. */ export function startCustomTouchCalibration(id: string): void; - /** * Sets the touch calibration pairs for a display. * These `pairs` would be used to calibrate the touch screen for display with `id` called in startCustomTouchCalibration(). @@ -10860,14 +12096,12 @@ export namespace Browser { * @throws Error */ export function completeCustomTouchCalibration(pairs: TouchCalibrationPairQuad, bounds: Bounds): void; - /** * Resets the touch calibration for the display and brings it back to its default state by clearing any touch calibration data associated with the display. * @since Chrome 57 * @param id The display's unique identifier. */ export function clearTouchCalibration(id: string): void; - /** * Sets the display mode to the specified mirror mode. * Each call resets the state from previous calls. @@ -10878,16 +12112,12 @@ export namespace Browser { */ export function setMirrorMode(info: MirrorModeInfo | MirrorModeInfoMixed, callback: () => void): void; export function setMirrorMode(info: MirrorModeInfo | MirrorModeInfoMixed): Promise; - /** Fired when anything changes to the display configuration. */ - export const onDisplayChanged: Browser.events.Event<() => void>; + export const onDisplayChanged: chrome.events.Event<() => void>; } - //////////////////// - // SystemLog - //////////////////// /** - * Use the `Browser.systemLog` API to record Chrome system logs from extensions. + * Use the `chrome.systemLog` API to record Chrome system logs from extensions. * * Permissions: "systemLog" * @@ -10908,11 +12138,8 @@ export namespace Browser { export function add(options: MessageOptions, callback: () => void): void; } - //////////////////// - // TabCapture - //////////////////// /** - * Use the `Browser.tabCapture` API to interact with tab media streams. + * Use the `chrome.tabCapture` API to interact with tab media streams. * * Permissions: "tabCapture" */ @@ -10952,7 +12179,8 @@ export namespace Browser { targetTabId?: number | undefined; } - export interface CaptureStatusChangedEvent extends Browser.events.Event<(info: CaptureInfo) => void> {} + export interface CaptureStatusChangedEvent extends chrome.events.Event<(info: CaptureInfo) => void> { + } /** * 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. @@ -10965,25 +12193,20 @@ export namespace Browser { * @param callback Callback invoked with CaptureInfo[] for captured tabs. */ 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. + * Creates a stream ID to capture the target tab. Similar to chrome.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. */ export function getMediaStreamId(options: GetMediaStreamOptions, 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; } - //////////////////// - // Tabs - //////////////////// /** - * Use the `Browser.tabs` API to interact with the browser's tab system. You can use this API to create, modify, and rearrange tabs in the browser. + * Use the `chrome.tabs` API to interact with the browser's tab system. You can use this API to create, modify, and rearrange tabs in the browser. * - * Permissions: The majority of the Browser.tabs API can be used without declaring any permission. However, the "tabs" permission is required in order to populate the url, title, and favIconUrl properties of Tab. + * Permissions: The majority of the chrome.tabs API can be used without declaring any permission. However, the "tabs" permission is required in order to populate the url, title, and favIconUrl properties of Tab. */ export namespace tabs { /** @@ -11058,7 +12281,7 @@ export namespace Browser { frozen: boolean; /** * Optional. - * The ID of the tab. Tab IDs are unique within a browser session. Under some circumstances a Tab may not be assigned an ID, for example when querying foreign tabs using the sessions API, in which case a session ID may be present. Tab ID can also be set to Browser.tabs.TAB_ID_NONE for apps and devtools windows. + * The ID of the tab. Tab IDs are unique within a browser session. Under some circumstances a Tab may not be assigned an ID, for example when querying foreign tabs using the sessions API, in which case a session ID may be present. Tab ID can also be set to chrome.tabs.TAB_ID_NONE for apps and devtools windows. */ id?: number | undefined; /** Whether the tab is in an incognito window. */ @@ -11145,45 +12368,6 @@ export namespace Browser { defaultZoomFactor?: number | undefined; } - export interface InjectDetails { - /** - * Optional. - * If allFrames is true, implies that the JavaScript or CSS should be injected into all frames of current page. By default, it's false and is only injected into the top frame. - */ - allFrames?: boolean | undefined; - /** - * Optional. JavaScript or CSS code to inject. - * Warning: Be careful using the code parameter. Incorrect use of it may open your extension to cross site scripting attacks. - */ - code?: string | undefined; - /** - * Optional. The soonest that the JavaScript or CSS will be injected into the tab. - * One of: "document_start", "document_end", or "document_idle" - * @since Chrome 20 - */ - runAt?: string | undefined; - /** Optional. JavaScript or CSS file to inject. */ - file?: string | undefined; - /** - * Optional. - * The frame where the script or CSS should be injected. Defaults to 0 (the top-level frame). - * @since Chrome 39 - */ - frameId?: number | undefined; - /** - * Optional. - * If matchAboutBlank is true, then the code is also injected in about:blank and about:srcdoc frames if your extension has access to its parent document. Code cannot be inserted in top-level about:-frames. By default it is false. - * @since Chrome 39 - */ - matchAboutBlank?: boolean | undefined; - /** - * Optional. The origin of the CSS to inject. This may only be specified for CSS, not JavaScript. Defaults to "author". - * One of: "author", or "user" - * @since Chrome 66 - */ - cssOrigin?: string | undefined; - } - export interface CreateProperties { /** Optional. The position the tab should take in the window. The provided value will be clamped to between zero and the number of tabs in the window. */ index?: number | undefined; @@ -11265,19 +12449,6 @@ export namespace Browser { autoDiscardable?: boolean | undefined; } - export interface CaptureVisibleTabOptions { - /** - * Optional. - * When format is "jpeg", controls the quality of the resulting image. This value is ignored for PNG images. As quality is decreased, the resulting image will have more visual artifacts, and the number of bytes needed to store it will decrease. - */ - quality?: number | undefined; - /** - * Optional. The format of an image. - * One of: "jpeg", or "png" - */ - format?: string | undefined; - } - export interface ReloadProperties { /** Optional. Whether using any local cache. Default is false. */ bypassCache?: boolean | undefined; @@ -11311,9 +12482,9 @@ export namespace Browser { export interface GroupOptions { /** Optional. Configurations for creating a group. Cannot be used if groupId is already specified. */ createProperties?: { - /** Optional. The window of the new group. Defaults to the current window. */ - windowId?: number | undefined; - } | undefined; + /** Optional. The window of the new group. Defaults to the current window. */ + windowId?: number | undefined; + } | undefined; /** Optional. The ID of the group to add the tabs to. If not specified, a new group will be created. */ groupId?: number | undefined; /** TOptional. he tab ID or list of tab IDs to add to the specified group. */ @@ -11393,7 +12564,7 @@ export namespace Browser { */ muted?: boolean | undefined; /** - * Optional. The ID of the group that the tabs are in, or Browser.tabGroups.TAB_GROUP_ID_NONE for ungrouped tabs. + * Optional. The ID of the group that the tabs are in, or chrome.tabGroups.TAB_GROUP_ID_NONE for ungrouped tabs. * @since Chrome 88 */ groupId?: number | undefined; @@ -11501,60 +12672,59 @@ export namespace Browser { zoomSettings: ZoomSettings; } - export interface TabHighlightedEvent extends Browser.events.Event<(highlightInfo: TabHighlightInfo) => void> {} + export interface TabHighlightedEvent extends chrome.events.Event<(highlightInfo: TabHighlightInfo) => void> { + } - export interface TabRemovedEvent - extends Browser.events.Event<(tabId: number, removeInfo: TabRemoveInfo) => void> - {} + export interface TabRemovedEvent extends chrome.events.Event<(tabId: number, removeInfo: TabRemoveInfo) => void> { + } - export interface TabUpdatedEvent - extends Browser.events.Event<(tabId: number, changeInfo: TabChangeInfo, tab: Tab) => void> - {} + export interface TabUpdatedEvent extends chrome.events.Event<(tabId: number, changeInfo: TabChangeInfo, tab: Tab) => void> { + } - export interface TabAttachedEvent - extends Browser.events.Event<(tabId: number, attachInfo: TabAttachInfo) => void> - {} + export interface TabAttachedEvent extends chrome.events.Event<(tabId: number, attachInfo: TabAttachInfo) => void> { + } - export interface TabMovedEvent extends Browser.events.Event<(tabId: number, moveInfo: TabMoveInfo) => void> {} + export interface TabMovedEvent extends chrome.events.Event<(tabId: number, moveInfo: TabMoveInfo) => void> { + } - export interface TabDetachedEvent - extends Browser.events.Event<(tabId: number, detachInfo: TabDetachInfo) => void> - {} + export interface TabDetachedEvent extends chrome.events.Event<(tabId: number, detachInfo: TabDetachInfo) => void> { + } - export interface TabCreatedEvent extends Browser.events.Event<(tab: Tab) => void> {} + export interface TabCreatedEvent extends chrome.events.Event<(tab: Tab) => void> { + } - export interface TabActivatedEvent extends Browser.events.Event<(activeInfo: TabActiveInfo) => void> {} + export interface TabActivatedEvent extends chrome.events.Event<(activeInfo: TabActiveInfo) => void> { + } - export interface TabReplacedEvent - extends Browser.events.Event<(addedTabId: number, removedTabId: number) => void> - {} + export interface TabReplacedEvent extends chrome.events.Event<(addedTabId: number, removedTabId: number) => void> { + } - export interface TabSelectedEvent - extends Browser.events.Event<(tabId: number, selectInfo: TabWindowInfo) => void> - {} + export interface TabSelectedEvent extends chrome.events.Event<(tabId: number, selectInfo: TabWindowInfo) => void> { + } - export interface TabZoomChangeEvent extends Browser.events.Event<(ZoomChangeInfo: ZoomChangeInfo) => void> {} + export interface TabZoomChangeEvent extends chrome.events.Event<(ZoomChangeInfo: ZoomChangeInfo) => void> { + } /** * Injects JavaScript code into a page. For details, see the programmatic injection section of the content scripts doc. * @param details Details of the script or CSS to inject. Either the code or the file property must be set, but both may not be set at the same time. * @return The `executeScript` method provides its result via callback or returned as a `Promise` (MV3 only). The result of the script in every injected frame. */ - export function executeScript(details: InjectDetails): Promise; + export function executeScript(details: extensionTypes.InjectDetails): Promise; /** * Injects JavaScript code into a page. For details, see the programmatic injection section of the content scripts doc. * @param details Details of the script or CSS to inject. Either the code or the file property must be set, but both may not be set at the same time. * @param callback Optional. Called after all the JavaScript has been executed. * Parameter result: The result of the script in every injected frame. */ - export function executeScript(details: InjectDetails, callback?: (result: any[]) => void): void; + export function executeScript(details: extensionTypes.InjectDetails, callback?: (result: any[]) => void): void; /** * Injects JavaScript code into a page. For details, see the programmatic injection section of the content scripts doc. * @param tabId Optional. The ID of the tab in which to run the script; defaults to the active tab of the current window. * @param details Details of the script or CSS to inject. Either the code or the file property must be set, but both may not be set at the same time. * @return The `executeScript` method provides its result via callback or returned as a `Promise` (MV3 only). The result of the script in every injected frame. */ - export function executeScript(tabId: number, details: InjectDetails): Promise; + export function executeScript(tabId: number, details: extensionTypes.InjectDetails): Promise; /** * Injects JavaScript code into a page. For details, see the programmatic injection section of the content scripts doc. * @param tabId Optional. The ID of the tab in which to run the script; defaults to the active tab of the current window. @@ -11562,7 +12732,7 @@ export namespace Browser { * @param callback Optional. Called after all the JavaScript has been executed. * Parameter result: The result of the script in every injected frame. */ - export function executeScript(tabId: number, details: InjectDetails, callback?: (result: any[]) => void): void; + export function executeScript(tabId: number, details: extensionTypes.InjectDetails, callback?: (result: any[]) => void): void; /** Retrieves details about the specified tab. */ export function get(tabId: number, callback: (tab: Tab) => void): void; /** @@ -11737,24 +12907,21 @@ export namespace Browser { * @param options Optional. Details about the format and quality of an image. * @return The `captureVisibleTab` method provides its result via callback or returned as a `Promise` (MV3 only). A data URL which encodes an image of the visible area of the captured tab. May be assigned to the 'src' property of an HTML Image element for display. */ - export function captureVisibleTab(options: CaptureVisibleTabOptions): Promise; + export function captureVisibleTab(options: extensionTypes.ImageDetails): Promise; /** * Captures the visible area of the currently active tab in the specified window. You must have permission to use this method. * @param options Optional. Details about the format and quality of an image. * @param callback * Parameter dataUrl: A data URL which encodes an image of the visible area of the captured tab. May be assigned to the 'src' property of an HTML Image element for display. */ - export function captureVisibleTab(options: CaptureVisibleTabOptions, callback: (dataUrl: string) => void): void; + export function captureVisibleTab(options: extensionTypes.ImageDetails, callback: (dataUrl: string) => void): void; /** * Captures the visible area of the currently active tab in the specified window. You must have permission to use this method. * @param windowId Optional. The target window. Defaults to the current window. * @param options Optional. Details about the format and quality of an image. * @return The `captureVisibleTab` method provides its result via callback or returned as a `Promise` (MV3 only). A data URL which encodes an image of the visible area of the captured tab. May be assigned to the 'src' property of an HTML Image element for display. */ - export function captureVisibleTab( - windowId: number, - options: CaptureVisibleTabOptions, - ): Promise; + export function captureVisibleTab(windowId: number, options: extensionTypes.ImageDetails): Promise; /** * Captures the visible area of the currently active tab in the specified window. You must have permission to use this method. * @param windowId Optional. The target window. Defaults to the current window. @@ -11762,11 +12929,7 @@ export namespace Browser { * @param callback * Parameter dataUrl: A data URL which encodes an image of the visible area of the captured tab. May be assigned to the 'src' property of an HTML Image element for display. */ - export function captureVisibleTab( - windowId: number, - options: CaptureVisibleTabOptions, - callback: (dataUrl: string) => void, - ): void; + export function captureVisibleTab(windowId: number, options: extensionTypes.ImageDetails, callback: (dataUrl: string) => void): void; /** * Reload a tab. * @since Chrome 16 @@ -11832,23 +12995,14 @@ export namespace Browser { * Sends a single message to the content script(s) in the specified tab, with an optional callback to run when a response is sent back. The runtime.onMessage event is fired in each content script running in the specified tab for the current extension. * @since Chrome 20 */ - export function sendMessage( - tabId: number, - message: M, - responseCallback: (response: R) => void, - ): void; + export function sendMessage(tabId: number, message: M, responseCallback: (response: R) => void): void; /** * Sends a single message to the content script(s) in the specified tab, with an optional callback to run when a response is sent back. The runtime.onMessage event is fired in each content script running in the specified tab for the current extension. * @since Chrome 41 * @param responseCallback Optional. * Parameter response: The JSON response object sent by the handler of the message. If an error occurs while connecting to the specified tab, the callback will be called with no arguments and runtime.lastError will be set to the error message. */ - export function sendMessage( - tabId: number, - message: M, - options: MessageSendOptions, - responseCallback: (response: R) => void, - ): void; + export function sendMessage(tabId: number, message: M, options: MessageSendOptions, responseCallback: (response: R) => void): void; /** * Sends a single message to the content script(s) in the specified tab, with an optional callback to run when a response is sent back. The runtime.onMessage event is fired in each content script running in the specified tab for the current extension. * @since Chrome 99 @@ -11858,22 +13012,14 @@ export namespace Browser { * Sends a single message to the content script(s) in the specified tab, with an optional callback to run when a response is sent back. The runtime.onMessage event is fired in each content script running in the specified tab for the current extension. * @since Chrome 99 */ - export function sendMessage( - tabId: number, - message: M, - options: MessageSendOptions, - ): Promise; + export function sendMessage(tabId: number, message: M, options: MessageSendOptions): Promise; /** * Sends a single request to the content script(s) in the specified tab, with an optional callback to run when a response is sent back. The extension.onRequest event is fired in each content script running in the specified tab for the current extension. * @deprecated since Chrome 33. Please use runtime.sendMessage. * @param responseCallback Optional. * Parameter response: The JSON response object sent by the handler of the request. If an error occurs while connecting to the specified tab, the callback will be called with no arguments and runtime.lastError will be set to the error message. */ - export function sendRequest( - tabId: number, - request: Request, - responseCallback?: (response: Response) => void, - ): void; + export function sendRequest(tabId: number, request: Request, responseCallback?: (response: Response) => void): void; /** Connects to the content script(s) in the specified tab. The runtime.onConnect event is fired in each content script running in the specified tab for the current extension. */ export function connect(tabId: number, connectInfo?: ConnectInfo): runtime.Port; /** @@ -11881,43 +13027,40 @@ export namespace Browser { * @param details Details of the script or CSS to inject. Either the code or the file property must be set, but both may not be set at the same time. * @return The `insertCSS` method provides its result via callback or returned as a `Promise` (MV3 only). It has no parameters. */ - export function insertCSS(details: InjectDetails): Promise; + export function insertCSS(details: extensionTypes.InjectDetails): Promise; /** * Injects CSS into a page. For details, see the programmatic injection section of the content scripts doc. * @param details Details of the script or CSS to inject. Either the code or the file property must be set, but both may not be set at the same time. * @param callback Optional. Called when all the CSS has been inserted. */ - export function insertCSS(details: InjectDetails, callback: () => void): void; + export function insertCSS(details: extensionTypes.InjectDetails, callback: () => void): void; /** * Injects CSS into a page. For details, see the programmatic injection section of the content scripts doc. * @param tabId Optional. The ID of the tab in which to insert the CSS; defaults to the active tab of the current window. * @param details Details of the script or CSS to inject. Either the code or the file property must be set, but both may not be set at the same time. * @return The `insertCSS` method provides its result via callback or returned as a `Promise` (MV3 only). It has no parameters. */ - export function insertCSS(tabId: number, details: InjectDetails): Promise; + export function insertCSS(tabId: number, details: extensionTypes.InjectDetails): Promise; /** * Injects CSS into a page. For details, see the programmatic injection section of the content scripts doc. * @param tabId Optional. The ID of the tab in which to insert the CSS; defaults to the active tab of the current window. * @param details Details of the script or CSS to inject. Either the code or the file property must be set, but both may not be set at the same time. * @param callback Optional. Called when all the CSS has been inserted. */ - export function insertCSS(tabId: number, details: InjectDetails, callback: () => void): void; + export function insertCSS(tabId: number, details: extensionTypes.InjectDetails, callback: () => void): void; /** * Highlights the given tabs. * @since Chrome 16 * @return The `highlight` method provides its result via callback or returned as a `Promise` (MV3 only). Contains details about the window whose tabs were highlighted. */ - export function highlight(highlightInfo: HighlightInfo): Promise; + export function highlight(highlightInfo: HighlightInfo): Promise; /** * Highlights the given tabs. * @since Chrome 16 * @param callback Optional. * Parameter window: Contains details about the window whose tabs were highlighted. */ - export function highlight( - highlightInfo: HighlightInfo, - callback: (window: Browser.windows.Window) => void, - ): void; + export function highlight(highlightInfo: HighlightInfo, callback: (window: chrome.windows.Window) => void): void; /** * Gets all tabs that have the specified properties, or all tabs if no properties are specified. * @since Chrome 16 @@ -12220,19 +13363,433 @@ export namespace Browser { * @since Chrome 38 */ export var onZoomChange: TabZoomChangeEvent; - /** * An ID which represents the absence of a browser tab. * @since Chrome 46 */ export var TAB_ID_NONE: -1; + + /** Tab sharing state for screen, microphone and camera. */ + interface SharingState { + /** + * If the tab is sharing the screen the value will be one of "Screen", "Window", or "Application", or undefined if not screen sharing. + */ + screen?: string | undefined; + /** True if the tab is using the camera. */ + camera: boolean; + /** True if the tab is using the microphone. */ + microphone: boolean; + } + + /** Defines the page settings to be used when saving a page as a pdf file. */ + interface PageSettings { + /** The name of the file. May include optional .pdf extension. */ + toFileName?: string | undefined; + /** The page size unit: 0 = inches, 1 = millimeters. Default: 0. */ + paperSizeUnit?: number | undefined; + /** The paper width in paper size units. Default: 8.5. */ + paperWidth?: number | undefined; + /** The paper height in paper size units. Default: 11.0. */ + paperHeight?: number | undefined; + /** The page content orientation: 0 = portrait, 1 = landscape. Default: 0. */ + orientation?: number | undefined; + /** The page content scaling factor: 1.0 = 100% = normal size. Default: 1.0. */ + scaling?: number | undefined; + /** Whether the page content should shrink to fit the page width (overrides scaling). Default: true. */ + shrinkToFit?: boolean | undefined; + /** Whether the page background colors should be shown. Default: false. */ + showBackgroundColors?: boolean | undefined; + /** Whether the page background images should be shown. Default: false. */ + showBackgroundImages?: boolean | undefined; + /** The spacing between the left header/footer and the left edge of the paper (inches). Default: 0. */ + edgeLeft?: number | undefined; + /** The spacing between the right header/footer and the right edge of the paper (inches). Default: 0. */ + edgeRight?: number | undefined; + /** The spacing between the top of the headers and the top edge of the paper (inches). Default: 0 */ + edgeTop?: number | undefined; + /** The spacing between the bottom of the footers and the bottom edge of the paper (inches). Default: 0. */ + edgeBottom?: number | undefined; + /** The margin between the page content and the left edge of the paper (inches). Default: 0.5. */ + marginLeft?: number | undefined; + /** The margin between the page content and the right edge of the paper (inches). Default: 0.5. */ + marginRight?: number | undefined; + /** The margin between the page content and the top edge of the paper (inches). Default: 0.5. */ + marginTop?: number | undefined; + /** The margin between the page content and the bottom edge of the paper (inches). Default: 0.5. */ + marginBottom?: number | undefined; + /** The text for the page's left header. Default: '&T'. */ + headerLeft?: string | undefined; + /** The text for the page's center header. Default: ''. */ + headerCenter?: string | undefined; + /** The text for the page's right header. Default: '&U'. */ + headerRight?: string | undefined; + /** The text for the page's left footer. Default: '&PT'. */ + footerLeft?: string | undefined; + /** The text for the page's center footer. Default: ''. */ + footerCenter?: string | undefined; + /** The text for the page's right footer. Default: '&D'. */ + footerRight?: string | undefined; + } + + /** An object describing filters to apply to tabs.onUpdated events. */ + interface UpdateFilter { + /** + * A list of URLs or URL patterns. Events that cannot match any of the URLs will be filtered out. Filtering with urls requires the `"tabs"` or `"activeTab"` permission. + */ + urls?: string[] | undefined; + /** A list of property names. Events that do not match any of the names will be filtered out. */ + properties?: UpdatePropertyName[] | undefined; + tabId?: number | undefined; + windowId?: number | undefined; + } + + interface _ConnectConnectInfo { + /** Will be passed into onConnect for content scripts that are listening for the connection event. */ + name?: string | undefined; + /** Open a port to a specific frame identified by `frameId` instead of all frames in the tab. */ + frameId?: number | undefined; + } + + interface _SendMessageOptions { + /** Send a message to a specific frame identified by `frameId` instead of all frames in the tab. */ + frameId?: number | undefined; + } + + interface _CreateCreateProperties { + /** The window to create the new tab in. Defaults to the current window. */ + windowId?: number | undefined; + /** + * The position the tab should take in the window. The provided value will be clamped to between zero and the number of tabs in the window. + */ + index?: number | undefined; + /** + * The URL to navigate the tab to initially. Fully-qualified URLs must include a scheme (i.e. 'http://www.google.com', not 'www.google.com'). Relative URLs will be relative to the current page within the extension. Defaults to the New Tab Page. + */ + url?: string | undefined; + /** + * Whether the tab should become the active tab in the window. Does not affect whether the window is focused (see `windows.update`). Defaults to `true`. + */ + active?: boolean | undefined; + /** Whether the tab should be pinned. Defaults to `false` */ + pinned?: boolean | undefined; + /** + * The ID of the tab that opened this tab. If specified, the opener tab must be in the same window as the newly created tab. + */ + openerTabId?: number | undefined; + /** The CookieStoreId for the tab that opened this tab. */ + cookieStoreId?: string | undefined; + /** Whether the document in the tab should be opened in reader mode. */ + openInReaderMode?: boolean | undefined; + /** Whether the tab is marked as 'discarded' when created. */ + discarded?: boolean | undefined; + /** The title used for display if the tab is created in discarded mode. */ + title?: string | undefined; + /** Whether the tab should be muted when created. */ + muted?: boolean | undefined; + } + + interface _DuplicateDuplicateProperties { + /** + * The position the new tab should take in the window. The provided value will be clamped to between zero and the number of tabs in the window. + */ + index?: number | undefined; + /** + * Whether the tab should become the active tab in the window. Does not affect whether the window is focused (see `windows.update`). Defaults to `true`. + */ + active?: boolean | undefined; + } + + interface _QueryQueryInfo { + /** Whether the tabs are active in their windows. */ + active?: boolean | undefined; + /** Whether the tabs are drawing attention. */ + attention?: boolean | undefined; + /** Whether the tabs are pinned. */ + pinned?: boolean | undefined; + /** Whether the tabs are audible. */ + audible?: boolean | undefined; + /** Whether the tab can be discarded automatically by the browser when resources are low. */ + autoDiscardable?: boolean | undefined; + /** Whether the tabs are muted. */ + muted?: boolean | undefined; + /** Whether the tabs are highlighted. Works as an alias of active. */ + highlighted?: boolean | undefined; + /** Whether the tabs are in the current window. */ + currentWindow?: boolean | undefined; + /** Whether the tabs are in the last focused window. */ + lastFocusedWindow?: boolean | undefined; + /** Whether the tabs have completed loading. */ + status?: TabStatus | undefined; + /** True while the tabs are not loaded with content. */ + discarded?: boolean | undefined; + /** True while the tabs are hidden. */ + hidden?: boolean | undefined; + /** Match page titles against a pattern. */ + title?: string | undefined; + /** Match tabs against one or more URL patterns. Note that fragment identifiers are not matched. */ + url?: string | string[] | undefined; + /** The ID of the parent window, or `windows.WINDOW_ID_CURRENT` for the current window. */ + windowId?: number | undefined; + /** The type of window the tabs are in. */ + windowType?: WindowType | undefined; + /** The position of the tabs within their windows. */ + index?: number | undefined; + /** The CookieStoreId used for the tab. */ + cookieStoreId?: string[] | string | undefined; + /** + * The ID of the tab that opened this tab. If specified, the opener tab must be in the same window as this tab. + */ + openerTabId?: number | undefined; + /** True for any screen sharing, or a string to specify type of screen sharing. */ + screen?: boolean | _QueryQueryInfoScreen | undefined; + /** True if the tab is using the camera. */ + camera?: boolean | undefined; + /** True if the tab is using the microphone. */ + microphone?: boolean | undefined; + } + + interface _HighlightHighlightInfo { + /** The window that contains the tabs. */ + windowId?: number | undefined; + /** + * If true, the `windows.Window` returned will have a `tabs` property that contains a list of the `tabs.Tab` objects. The `Tab` objects only contain the `url`, `title` and `favIconUrl` properties if the extension's manifest file includes the `"tabs"` permission. If false, the `windows.Window` won't have the `tabs` property. + */ + populate?: boolean | undefined; + /** One or more tab indices to highlight. */ + tabs: number[] | number; + } + + interface _UpdateUpdateProperties { + /** A URL to navigate the tab to. */ + url?: string | undefined; + /** + * Whether the tab should be active. Does not affect whether the window is focused (see `windows.update`). + */ + active?: boolean | undefined; + /** Whether the tab can be discarded automatically by the browser when resources are low. */ + autoDiscardable?: boolean | undefined; + /** Adds or removes the tab from the current selection. */ + highlighted?: boolean | undefined; + /** Whether the tab should be pinned. */ + pinned?: boolean | undefined; + /** Whether the tab should be muted. */ + muted?: boolean | undefined; + /** + * The ID of the tab that opened this tab. If specified, the opener tab must be in the same window as this tab. + */ + openerTabId?: number | undefined; + /** Whether the load should replace the current history entry for the tab. */ + loadReplace?: boolean | undefined; + /** + * The ID of this tab's successor. If specified, the successor tab must be in the same window as this tab. + */ + successorTabId?: number | undefined; + } + + interface _MoveMoveProperties { + /** Defaults to the window the tab is currently in. */ + windowId?: number | undefined; + /** The position to move the window to. -1 will place the tab at the end of the window. */ + index: number; + } + + interface _ReloadReloadProperties { + /** Whether using any local cache. Default is false. */ + bypassCache?: boolean | undefined; + } + + interface _MoveInSuccessionOptions { + /** Whether to move the tabs before (false) or after (true) tabId in the succession. Defaults to false. */ + append?: boolean | undefined; + /** + * Whether to link up the current predecessors or successor (depending on options.append) of tabId to the other side of the chain after it is prepended or appended. If true, one of the following happens: if options.append is false, the first tab in the array is set as the successor of any current predecessors of tabId; if options.append is true, the current successor of tabId is set as the successor of the last tab in the array. Defaults to false. + */ + insert?: boolean | undefined; + } + + /** Lists the changes to the state of the tab that was updated. */ + interface _OnUpdatedChangeInfo { + /** The tab's new attention state. */ + attention?: boolean | undefined; + /** The tab's new audible state. */ + audible?: boolean | undefined; + /** The tab's new autoDiscardable state. */ + autoDiscardable?: boolean | undefined; + /** True while the tab is not loaded with content. */ + discarded?: boolean | undefined; + /** + * The tab's new favicon URL. This property is only present if the extension's manifest includes the `"tabs"` permission. + */ + favIconUrl?: string | undefined; + /** The tab's new hidden state. */ + hidden?: boolean | undefined; + /** Whether the document in the tab can be rendered in reader mode. */ + isArticle?: boolean | undefined; + /** The tab's new muted state and the reason for the change. */ + mutedInfo?: MutedInfo | undefined; + /** The tab's new pinned state. */ + pinned?: boolean | undefined; + /** The tab's new sharing state for screen, microphone and camera. */ + sharingState?: SharingState | undefined; + /** The status of the tab. Can be either _loading_ or _complete_. */ + status?: string | undefined; + /** + * The title of the tab if it has changed. This property is only present if the extension's manifest includes the `"tabs"` permission. + */ + title?: string | undefined; + /** + * The tab's URL if it has changed. This property is only present if the extension's manifest includes the `"tabs"` permission. + */ + url?: string | undefined; + } + + interface _TabsOnUpdatedEvent void> { + addListener(cb: TCallback, filter?: UpdateFilter): void; + removeListener(cb: TCallback): void; + hasListener(cb: TCallback): boolean; + } + + interface _OnMovedMoveInfo { + windowId: number; + fromIndex: number; + toIndex: number; + } + + interface _OnActivatedActiveInfo { + /** The ID of the tab that has become active. */ + tabId: number; + /** The ID of the tab that was previously active, if that tab is still open. */ + previousTabId?: number | undefined; + /** The ID of the window the active tab changed inside of. */ + windowId: number; + } + + interface _OnHighlightedHighlightInfo { + /** The window whose tabs changed. */ + windowId: number; + /** All highlighted tabs in the window. */ + tabIds: number[]; + } + + interface _OnDetachedDetachInfo { + oldWindowId: number; + oldPosition: number; + } + + interface _OnAttachedAttachInfo { + newWindowId: number; + newPosition: number; + } + + interface _OnRemovedRemoveInfo { + /** The window whose tab is closed. */ + windowId: number; + /** True when the tab is being closed because its window is being closed. */ + isWindowClosing: boolean; + } + + interface _OnZoomChangeZoomChangeInfo { + tabId: number; + oldZoomFactor: number; + newZoomFactor: number; + zoomSettings: ZoomSettings; + } + + /** + * Warm up a tab + * @param tabId The ID of the tab to warm up. + */ + function warmup(tabId: number): Promise; + /** + * Toggles reader mode for the document in the tab. + * @param [tabId] Defaults to the active tab of the current window. + */ + function toggleReaderMode(tabId?: number): Promise; + /** Captures an area of a specified tab. You must have permission to use this method. */ + function captureTab(): Promise; + /** + * Captures an area of a specified tab. You must have permission to use this method. + * @param tabId The tab to capture. Defaults to the active tab of the current window. + */ + function captureTab(tabId: number, options?: extensionTypes.ImageDetails): Promise; + /** Captures an area of a specified tab. You must have permission to use this method. */ + function captureTab(options: extensionTypes.ImageDetails): Promise; + /** + * Removes injected CSS from a page. For details, see the programmatic injection section of the content scripts doc. + * @param details Details of the CSS text to remove. + * Not supported on manifest versions above 2. + */ + function removeCSS(details: extensionTypes.InjectDetails): Promise; + /** + * Removes injected CSS from a page. For details, see the programmatic injection section of the content scripts doc. + * @param tabId The ID of the tab from which to remove the injected CSS; defaults to the active tab of the current window. + * @param details Details of the CSS text to remove. + * Not supported on manifest versions above 2. + */ + function removeCSS(tabId: number, details: extensionTypes.InjectDetails): Promise; + /** Prints page in active tab. */ + function print(): void; + /** Shows print preview for page in active tab. */ + function printPreview(): Promise; + /** + * Saves page in active tab as a PDF file. + * @param pageSettings The page settings used to save the PDF file. + */ + function saveAsPDF(pageSettings: PageSettings): Promise; + /** + * Shows one or more tabs. + * @param tabIds The TAB ID or list of TAB IDs to show. + */ + function show(tabIds: number | number[]): Promise; + /** + * Hides one or more tabs. The `"tabHide"` permission is required to hide tabs. Not all tabs are hidable. Returns an array of hidden tabs. + * @param tabIds The TAB ID or list of TAB IDs to hide. + */ + function hide(tabIds: number | number[]): Promise; + /** + * Removes an array of tabs from their lines of succession and prepends or appends them in a chain to another tab. + * @param tabIds An array of tab IDs to move in the line of succession. For each tab in the array, the tab's current predecessors will have their successor set to the tab's current successor, and each tab will then be set to be the successor of the previous tab in the array. Any tabs not in the same window as the tab indicated by the second argument (or the first tab in the array, if no second argument) will be skipped. + * @param [tabId] The ID of a tab to set as the successor of the last tab in the array, or `tabs.TAB_ID_NONE` to leave the last tab without a successor. If options.append is true, then this tab is made the predecessor of the first tab in the array instead. + */ + function moveInSuccession(tabIds: number[], tabId?: number, options?: _MoveInSuccessionOptions): Promise; + + /** An ID which represents the absence of a browser tab. */ + const TAB_ID_NONE: number; + /** + * Fired when a tab is created. Note that the tab's URL may not be set at the time this event fired, but you can listen to onUpdated events to be notified when a URL is set. + * @param tab Details of the tab that was created. + */ + const onCreated: WebExtEvent<(tab: Tab) => void>; + /** + * Fired when a tab is updated. + * @param changeInfo Lists the changes to the state of the tab that was updated. + * @param tab Gives the state of the tab that was updated. + */ + const onUpdated: _TabsOnUpdatedEvent; + /** + * Fired when a tab is moved within a window. Only one move event is fired, representing the tab the user directly moved. Move events are not fired for the other tabs that must move in response. This event is not fired when a tab is moved between windows. For that, see `tabs.onDetached`. + */ + const onMoved: WebExtEvent<(tabId: number, moveInfo: _OnMovedMoveInfo) => void>; + /** + * Fires when the active tab in a window changes. Note that the tab's URL may not be set at the time this event fired, but you can listen to onUpdated events to be notified when a URL is set. + */ + const onActivated: WebExtEvent<(activeInfo: _OnActivatedActiveInfo) => void>; + /** Fired when the highlighted or selected tabs in a window changes. */ + const onHighlighted: WebExtEvent<(highlightInfo: _OnHighlightedHighlightInfo) => void>; + /** Fired when a tab is detached from a window, for example because it is being moved between windows. */ + const onDetached: WebExtEvent<(tabId: number, detachInfo: _OnDetachedDetachInfo) => void>; + /** Fired when a tab is attached to a window, for example because it was moved between windows. */ + const onAttached: WebExtEvent<(tabId: number, attachInfo: _OnAttachedAttachInfo) => void>; + /** Fired when a tab is closed. */ + const onRemoved: WebExtEvent<(tabId: number, removeInfo: _OnRemovedRemoveInfo) => void>; + /** Fired when a tab is replaced with another tab due to prerendering or instant. */ + const onReplaced: WebExtEvent<(addedTabId: number, removedTabId: number) => void>; + /** Fired when a tab is zoomed. */ + const onZoomChange: WebExtEvent<(ZoomChangeInfo: _OnZoomChangeZoomChangeInfo) => void>; } - //////////////////// - // Tab Groups - //////////////////// /** - * Use the `Browser.tabGroups` API to interact with the browser's tab grouping system. You can use this API to modify and rearrange tab groups in the browser. To group and ungroup tabs, or to query what tabs are in groups, use the `Browser.tabs` API. + * Use the `chrome.tabGroups` API to interact with the browser's tab grouping system. You can use this API to modify and rearrange tab groups in the browser. To group and ungroup tabs, or to query what tabs are in groups, use the `chrome.tabs` API. * * Permissions: "tabGroups" * @since Chrome 89, MV3 @@ -12251,7 +13808,7 @@ export namespace Browser { PINK = "pink", PURPLE = "purple", RED = "red", - YELLOW = "yellow", + YELLOW = "yellow" } export interface TabGroup { @@ -12301,7 +13858,6 @@ export namespace Browser { */ export function get(groupId: number): Promise; export function get(groupId: number, callback: (group: TabGroup) => void): void; - /** * Moves the group and all its tabs within its window, or to a new window. * @param groupId The ID of the group to move. @@ -12309,12 +13865,7 @@ export namespace Browser { * Can return its result via Promise since Chrome 90. */ export function move(groupId: number, moveProperties: MoveProperties): Promise; - export function move( - groupId: number, - moveProperties: MoveProperties, - callback: (group?: TabGroup) => void, - ): void; - + export function move(groupId: number, moveProperties: MoveProperties, callback: (group?: TabGroup) => void): void; /** * Gets all groups that have the specified properties, or all groups if no properties are specified. * @@ -12322,7 +13873,6 @@ export namespace Browser { */ export function query(queryInfo: QueryInfo): Promise; export function query(queryInfo: QueryInfo, callback: (result: TabGroup[]) => void): void; - /** * Modifies the properties of a group. Properties that are not specified in `updateProperties` are not modified. * @param groupId The ID of the group to modify. @@ -12330,12 +13880,7 @@ export namespace Browser { * Can return its result via Promise since Chrome 90. */ export function update(groupId: number, updateProperties: UpdateProperties): Promise; - export function update( - groupId: number, - updateProperties: UpdateProperties, - callback: (group?: TabGroup) => void, - ): void; - + export function update(groupId: number, updateProperties: UpdateProperties, callback: (group?: TabGroup) => void): void; /** Fired when a group is created. */ export const onCreated: events.Event<(group: TabGroup) => void>; /** Fired when a group is moved within a window. Move events are still fired for the individual tabs within the group, as well as for the group itself. This event is not fired when a group is moved between windows; instead, it will be removed from one window and created in another. */ @@ -12346,11 +13891,8 @@ export namespace Browser { export const onUpdated: events.Event<(group: TabGroup) => void>; } - //////////////////// - // Top Sites - //////////////////// /** - * Use the `Browser.topSites` API to access the top sites (i.e. most visited sites) that are displayed on the new tab page. These do not include shortcuts customized by the user. + * Use the `chrome.topSites` API to access the top sites (i.e. most visited sites) that are displayed on the new tab page. These do not include shortcuts customized by the user. * * Permissions: "topSites" */ @@ -12365,19 +13907,36 @@ export namespace Browser { /** 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). */ export function get(): Promise; + + interface _GetOptions { + /** @deprecated Please use the other options to tune the results received from topSites. */ + providers?: string[] | undefined; + /** The number of top sites to return, defaults to the value used by Firefox */ + limit?: number | undefined; + /** Limit the result to a single top site link per domain */ + onePerDomain?: boolean | undefined; + /** Include sites that the user has blocked from appearing on the Firefox new tab. */ + includeBlocked?: boolean | undefined; + /** Include sites favicon if available. */ + includeFavicon?: boolean | undefined; + /** Include sites that the user has pinned on the Firefox new tab. */ + includePinned?: boolean | undefined; + /** Include search shortcuts appearing on the Firefox new tab. */ + includeSearchShortcuts?: boolean | undefined; + /** + * Return the sites that exactly appear on the user's new-tab page. When true, all other options are ignored except limit and includeFavicon. If the user disabled newtab Top Sites, the newtab parameter will be ignored. + */ + newtab?: boolean | undefined; + } } - //////////////////// - // Text to Speech - //////////////////// /** - * Use the `Browser.tts` API to play synthesized text-to-speech (TTS). See also the related {@link ttsEngine} API, which allows an extension to implement a speech engine. + * Use the `chrome.tts` API to play synthesized text-to-speech (TTS). See also the related {@link ttsEngine} API, which allows an extension to implement a speech engine. * * Permissions: "tts" */ @@ -12393,7 +13952,7 @@ export namespace Browser { CANCELLED = "cancelled", ERROR = "error", PAUSE = "pause", - RESUME = "resume", + RESUME = "resume" } /** An event from the TTS engine to communicate the status of an utterance. */ @@ -12444,8 +14003,8 @@ export namespace Browser { * @param event The update event from the text-to-speech engine indicating the status of this utterance. */ onEvent?: ( - event: TtsEvent, - ) => void; + event: TtsEvent, + ) => void; } /** A description of a voice available for speech synthesis. */ @@ -12467,10 +14026,10 @@ export namespace Browser { voiceName?: string; } - /** @deprecated since Chrome 70. Gender is deprecated and is ignored.*/ + /** @deprecated since Chrome 70. Gender is deprecated and is ignored. */ export enum VoiceGender { FEMALE = "female", - MALE = "male", + MALE = "male" } /** @@ -12480,7 +14039,6 @@ export namespace Browser { */ export function getVoices(): Promise; export function getVoices(callback: (voices: TtsVoice[]) => void): void; - /** * Checks whether the engine is currently speaking. On Mac OS X, the result is true whenever the system speech engine is speaking, even if the speech wasn't initiated by Chrome. * @@ -12488,39 +14046,31 @@ export namespace Browser { */ export function isSpeaking(): Promise; export function isSpeaking(callback: (speaking: boolean) => void): void; - /** Pauses speech synthesis, potentially in the middle of an utterance. A call to resume or stop will un-pause speech. */ export function pause(): void; - /** If speech was paused, resumes speaking where it left off. */ export function resume(): void; - /** * Speaks text using a text-to-speech engine. * @param utterance The text to speak, either plain text or a complete, well-formed SSML document. Speech engines that do not support SSML will strip away the tags and speak the text. The maximum length of the text is 32,768 characters. * @param options Optional. The speech options. - + * * Can return its result via Promise since Chrome Chrome 101 */ export function speak(utterance: string, options?: TtsOptions): Promise; export function speak(utterance: string, callback: () => void): void; export function speak(utterance: string, options: TtsOptions, callback: () => void): void; - /** Stops any current speech and flushes the queue of any pending utterances. In addition, if speech was paused, it will now be un-paused for the next call to speak. */ export function stop(): void; - /** * Called when the list of {@link TtsVoice} that would be returned by getVoices has changed. * @since Chrome 124 */ - const onVoicesChanged: Browser.events.Event<() => void>; + const onVoicesChanged: chrome.events.Event<() => void>; } - //////////////////// - // Text to Speech Engine - //////////////////// /** - * Use the `Browser.ttsEngine` API to implement a text-to-speech(TTS) engine using an extension. If your extension registers using this API, it will receive events containing an utterance to be spoken and other parameters when any extension or Chrome App uses the {@link tts} API to generate speech. Your extension can then use any available web technology to synthesize and output the speech, and send events back to the calling function to report the status. + * Use the `chrome.ttsEngine` API to implement a text-to-speech(TTS) engine using an extension. If your extension registers using this API, it will receive events containing an utterance to be spoken and other parameters when any extension or Chrome App uses the {@link tts} API to generate speech. Your extension can then use any available web technology to synthesize and output the speech, and send events back to the calling function to report the status. * * Permissions: "ttsEngine" */ @@ -12537,6 +14087,7 @@ export namespace Browser { /** True if this audio buffer is the last for the text being spoken. */ isLastBuffer?: boolean; } + /** * Contains the audio stream format expected to be produced by an engine. * @since Chrome 92 @@ -12556,7 +14107,7 @@ export namespace Browser { FAILED = "failed", INSTALLED = "installed", INSTALLING = "installing", - NOT_INSTALLED = "notInstalled", + NOT_INSTALLED = "notInstalled" } /** @@ -12620,7 +14171,7 @@ export namespace Browser { */ export enum TtsClientSource { CHROMEFEATURE = "chromefeature", - EXTENSION = "extension", + EXTENSION = "extension" } /** @@ -12629,7 +14180,7 @@ export namespace Browser { */ export enum VoiceGender { MALE = "male", - FEMALE = "female", + FEMALE = "female" } /** @@ -12637,68 +14188,55 @@ export namespace Browser { * @since Chrome 132 */ export function updateLanguage(status: LanguageStatus): void; - /** * Called by an engine to update its list of voices. This list overrides any voices declared in this extension's manifest. * @since Chrome 66 */ export function updateVoices(voices: tts.TtsVoice[]): void; - /** * Fired when a TTS client requests to install a new language. The engine should attempt to download and install the language, and call ttsEngine.updateLanguage with the result. On success, the engine should also call ttsEngine.updateVoices to register the newly available voices. * @since Chrome 131 */ - export const onInstallLanguageRequest: Browser.events.Event<(requestor: TtsClient, lang: string) => void>; - + export const onInstallLanguageRequest: chrome.events.Event<(requestor: TtsClient, lang: string) => void>; /** * Fired when a TTS client requests the install status of a language. * @since Chrome 132 */ - export const onLanguageStatusRequest: Browser.events.Event<(requestor: TtsClient, lang: string) => void>; - + export const onLanguageStatusRequest: chrome.events.Event<(requestor: TtsClient, lang: string) => void>; /** Optional: if an engine supports the pause event, it should pause the current utterance being spoken, if any, until it receives a resume event or stop event. Note that a stop event should also clear the paused state. */ - export const onPause: Browser.events.Event<() => void>; - + export const onPause: chrome.events.Event<() => void>; /** Optional: if an engine supports the pause event, it should also support the resume event, to continue speaking the current utterance, if any. Note that a stop event should also clear the paused state. */ - export const onResume: Browser.events.Event<() => void>; - + export const onResume: chrome.events.Event<() => void>; /** Called when the user makes a call to tts.speak() and one of the voices from this extension's manifest is the first to match the options object. */ - export const onSpeak: Browser.events.Event< - (utterance: string, options: SpeakOptions, sendTtsEvent: (event: Browser.tts.TtsEvent) => void) => void - >; - + export const onSpeak: chrome.events.Event< + (utterance: string, options: SpeakOptions, sendTtsEvent: (event: chrome.tts.TtsEvent) => void) => void + >; /** * Called when the user makes a call to tts.speak() and one of the voices from this extension's manifest is the first to match the options object. Differs from ttsEngine.onSpeak in that Chrome provides audio playback services and handles dispatching tts events. * @since Chrome 92 */ - - export const onSpeakWithAudioStream: Browser.events.Event< - ( - utterance: string, - options: SpeakOptions, - audioStreamOptions: AudioStreamOptions, - sendTtsAudio: (audioBufferParams: AudioBuffer) => void, - sendError: (errorMessage?: string) => void, - ) => void - >; - + export const onSpeakWithAudioStream: chrome.events.Event< + ( + utterance: string, + options: SpeakOptions, + audioStreamOptions: AudioStreamOptions, + sendTtsAudio: (audioBufferParams: AudioBuffer) => void, + sendError: (errorMessage?: string) => void, + ) => void + >; /** Fired when a call is made to tts.stop and this extension may be in the middle of speaking. If an extension receives a call to onStop and speech is already stopped, it should do nothing (not raise an error). If speech is in the paused state, this should cancel the paused state. */ - export const onStop: Browser.events.Event<() => void>; - + export const onStop: chrome.events.Event<() => void>; /** * Fired when a TTS client indicates a language is no longer needed. * @since Chrome 132 */ - export const onUninstallLanguageRequest: Browser.events.Event< - (requestor: TtsClient, lang: string, uninstallOptions: LanguageUninstallOptions) => void - >; + export const onUninstallLanguageRequest: chrome.events.Event< + (requestor: TtsClient, lang: string, uninstallOptions: LanguageUninstallOptions) => void + >; } - //////////////////// - // Types - //////////////////// /** - * The `Browser.types` API contains type declarations for Chrome. + * The `chrome.types` API contains type declarations for Chrome. */ export namespace types { /** @@ -12710,7 +14248,6 @@ export namespace Browser { * @since Chrome 44 */ export type ChromeSettingScope = "regular" | "regular_only" | "incognito_persistent" | "incognito_session_only"; - /** * One of * * `not_controllable`: cannot be controlled by any extension @@ -12719,11 +14256,10 @@ export namespace Browser { * * `controlled_by_this_extension`: controlled by this extension * @since Chrome 44 */ - export type LevelOfControl = - | "not_controllable" - | "controlled_by_other_extensions" - | "controllable_by_this_extension" - | "controlled_by_this_extension"; + export type LevelOfControl = | "not_controllable" + | "controlled_by_other_extensions" + | "controllable_by_this_extension" + | "controlled_by_this_extension"; /** Which setting to change. */ export interface ChromeSettingSetDetails { @@ -12776,80 +14312,143 @@ export namespace Browser { /** * An interface that allows access to a Chrome browser setting. - * See {@link Browser.accessibilityFeatures} for an example. + * See {@link chrome.accessibilityFeatures} for an example. */ export interface ChromeSetting { + /** Fired after the setting changes. */ + onChange: chrome.events.Event<(details: ChromeSettingOnChangeDetails) => void>; /** * 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; - /** * 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>; - /** * 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; - - /** Fired after the setting changes. */ - onChange: Browser.events.Event<(details: ChromeSettingOnChangeDetails) => void>; } - } - //////////////////// - // VPN Provider - //////////////////// - /** - * Use the `Browser.vpnProvider` API to implement a VPN client. - * - * Permissions: "vpnProvider" - * @platform ChromeOS only - * @since Chrome 43 - */ - export namespace vpnProvider { - export interface VpnSessionParameters { - /** 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) */ - broadcastAddress?: string | undefined; - /** Optional. MTU setting for the VPN interface. (default: 1500 bytes) */ - mtu?: string | undefined; + interface Setting { + /** Fired after the setting changes. */ + onChange: WebExtEvent<(details: _OnChangeDetails) => void>; /** - * 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. + * Gets the value of a setting. + * @param details Which setting to consider. */ - exclusionList: string[]; + get(details: _GetDetails): Promise<_GetReturnDetails>; /** - * 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. + * Sets the value of a setting. + * @param details Which setting to change. */ - inclusionList: string[]; - /** Optional. A list of search domains. (default: no search domain) */ - domainSearch?: string[] | undefined; - /** A list of IPs for the DNS servers. */ - dnsServer: string[]; + set(details: _SetDetails): Promise; + /** + * Clears the setting, restoring any default value. + * @param details Which setting to clear. + */ + clear(details: _ClearDetails): Promise; } - export interface VpnPlatformMessageEvent - extends Browser.events.Event<(id: string, message: string, error: string) => void> - {} - - export interface VpnPacketReceptionEvent extends Browser.events.Event<(data: ArrayBuffer) => void> {} + /** Details of the currently effective value. */ + interface _GetReturnDetails { + /** The value of the setting. */ + value: any; + /** The level of control of the setting. */ + levelOfControl: LevelOfControl; + /** + * Whether the effective value is specific to the incognito session. + * This property will _only_ be present if the `incognito` property in the `details` parameter of `get()` was true. + */ + incognitoSpecific?: boolean | undefined; + } - export interface VpnConfigRemovalEvent extends Browser.events.Event<(id: string) => void> {} + /** Which setting to consider. */ + interface _GetDetails { + /** Whether to return the value that applies to the incognito session (default false). */ + incognito?: boolean | undefined; + } + + /** Which setting to change. */ + interface _SetDetails { + /** + * The value of the setting. + * Note that every setting has a specific value type, which is described together with the setting. An extension should _not_ set a value of a different type. + */ + value: any; + /** Where to set the setting (default: regular). */ + scope?: SettingScope | undefined; + } + + /** Which setting to clear. */ + interface _ClearDetails { + /** Where to clear the setting (default: regular). */ + scope?: SettingScope | undefined; + } + + interface _OnChangeDetails { + /** The value of the setting after the change. */ + value: any; + /** The level of control of the setting. */ + levelOfControl: LevelOfControl; + /** + * Whether the value that has changed is specific to the incognito session. + * This property will _only_ be present if the user has enabled the extension in incognito mode. + */ + incognitoSpecific?: boolean | undefined; + } + } + + /** + * Use the `chrome.vpnProvider` API to implement a VPN client. + * + * Permissions: "vpnProvider" + * @platform ChromeOS only + * @since Chrome 43 + */ + export namespace vpnProvider { + export interface VpnSessionParameters { + /** 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) */ + broadcastAddress?: string | undefined; + /** Optional. 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. + */ + 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. + */ + inclusionList: string[]; + /** Optional. A list of search domains. (default: no search domain) */ + domainSearch?: string[] | undefined; + /** A list of IPs for the DNS servers. */ + dnsServer: string[]; + } + + export interface VpnPlatformMessageEvent extends chrome.events.Event<(id: string, message: string, error: string) => void> { + } + + export interface VpnPacketReceptionEvent extends chrome.events.Event<(data: ArrayBuffer) => void> { + } + + export interface VpnConfigRemovalEvent extends chrome.events.Event<(id: string) => void> { + } - export interface VpnConfigCreationEvent - extends Browser.events.Event<(id: string, name: string, data: { [key: string]: unknown }) => void> - {} + export interface VpnConfigCreationEvent extends chrome.events.Event<(id: string, name: string, data: { [key: string]: unknown }) => void> { + } - export interface VpnUiEvent extends Browser.events.Event<(event: string, id?: string) => void> {} + export interface VpnUiEvent extends chrome.events.Event<(event: string, id?: string) => void> { + } /** * Creates a new VPN configuration that persists across multiple login sessions of the user. @@ -12884,7 +14483,6 @@ export namespace Browser { * @param callback Optional. Called when the notification is complete or if there is an error. */ export function notifyConnectionStateChanged(state: string, callback?: () => void): void; - /** Triggered when a message is received from the platform for a VPN configuration owned by the extension. */ export var onPlatformMessage: VpnPlatformMessageEvent; /** Triggered when an IP packet is received via the tunnel for the VPN session owned by the extension. */ @@ -12897,11 +14495,8 @@ export namespace Browser { export var onUIEvent: VpnUiEvent; } - //////////////////// - // Wallpaper - //////////////////// /** - * Use the `Browser.wallpaper` API to change the ChromeOS wallpaper. + * Use the `chrome.wallpaper` API to change the ChromeOS wallpaper. * * Permissions: "wallpaper" * @platform ChromeOS only @@ -12932,11 +14527,113 @@ export namespace Browser { export function setWallpaper(details: WallpaperDetails, callback: (thumbnail?: ArrayBuffer) => void): void; } - //////////////////// - // Web Navigation - //////////////////// /** - * Use the `Browser.webNavigation` API to receive notifications about the status of navigation requests in-flight. + * The `chrome.webAuthenticationProxy` API lets remote desktop software running on a remote host intercept Web Authentication API (WebAuthn) requests in order to handle them on a local client. + * + * Permissions: "webAuthenticationProxy" + * @since Chrome 115, MV3 + */ + export namespace webAuthenticationProxy { + export interface CreateRequest { + /** The `PublicKeyCredentialCreationOptions` passed to `navigator.credentials.create()`, serialized as a JSON string. The serialization format is compatible with [`PublicKeyCredential.parseCreationOptionsFromJSON()`](https://w3c.github.io/webauthn/#sctn-parseCreationOptionsFromJSON). */ + requestDetailsJson: string; + /** An opaque identifier for the request. */ + requestId: number; + } + + export interface CreateResponseDetails { + /** The `DOMException` yielded by the remote request, if any. */ + error?: DOMExceptionDetails | undefined; + /** The `requestId` of the `CreateRequest`. */ + requestId: number; + /** The `PublicKeyCredential`, yielded by the remote request, if any, serialized as a JSON string by calling [`PublicKeyCredential.toJSON()`](https://w3c.github.io/webauthn/#dom-publickeycredential-tojson). */ + responseJson?: string | undefined; + } + + export interface DOMExceptionDetails { + name: string; + message: string; + } + + export interface GetRequest { + /** The `PublicKeyCredentialRequestOptions` passed to `navigator.credentials.get()`, serialized as a JSON string. The serialization format is compatible with [`PublicKeyCredential.parseRequestOptionsFromJSON()`](https://w3c.github.io/webauthn/#sctn-parseRequestOptionsFromJSON). */ + requestDetailsJson: string; + /** An opaque identifier for the request. */ + requestId: number; + } + + export interface GetResponseDetails { + /** The `DOMException` yielded by the remote request, if any. */ + error?: DOMExceptionDetails | undefined; + /** The `requestId` of the `CreateRequest`. */ + requestId: number; + /** The `PublicKeyCredential`, yielded by the remote request, if any, serialized as a JSON string by calling [`PublicKeyCredential.toJSON()`](https://w3c.github.io/webauthn/#dom-publickeycredential-tojson). */ + responseJson?: string | undefined; + } + + export interface IsUvpaaRequest { + /** An opaque identifier for the request. */ + requestId: number; + } + + export interface IsUvpaaResponseDetails { + isUvpaa: boolean; + requestId: number; + } + + /** + * Makes this extension the active Web Authentication API request proxy. + * + * Remote desktop extensions typically call this method after detecting attachment of a remote session to this host. Once this method returns without error, regular processing of WebAuthn requests is suspended, and events from this extension API are raised. + * + * This method fails with an error if a different extension is already attached. + * + * The attached extension must call `detach()` once the remote desktop session has ended in order to resume regular WebAuthn request processing. Extensions automatically become detached if they are unloaded. + * + * Refer to the `onRemoteSessionStateChange` event for signaling a change of remote session attachment from a native application to to the (possibly suspended) extension. + */ + export function attach(): Promise; + export function attach(callback: (error?: string | undefined) => void): void; + /** Reports the result of a `navigator.credentials.create()` call. The extension must call this for every `onCreateRequest` event it has received, unless the request was canceled (in which case, an `onRequestCanceled` event is fired). */ + export function completeCreateRequest(details: CreateResponseDetails): Promise; + export function completeCreateRequest(details: CreateResponseDetails, callback: () => void): void; + /** Reports the result of a `navigator.credentials.get()` call. The extension must call this for every `onGetRequest` event it has received, unless the request was canceled (in which case, an `onRequestCanceled` event is fired). */ + export function completeGetRequest(details: GetResponseDetails): Promise; + export function completeGetRequest(details: GetResponseDetails, callback: () => void): void; + /** Reports the result of a `PublicKeyCredential.isUserVerifyingPlatformAuthenticator()` call. The extension must call this for every `onIsUvpaaRequest` event it has received. */ + export function completeIsUvpaaRequest(details: IsUvpaaResponseDetails): Promise; + export function completeIsUvpaaRequest(details: IsUvpaaResponseDetails, callback: () => void): void; + /** + * Removes this extension from being the active Web Authentication API request proxy. + * + * This method is typically called when the extension detects that a remote desktop session was terminated. Once this method returns, the extension ceases to be the active Web Authentication API request proxy. + * + * Refer to the `onRemoteSessionStateChange` event for signaling a change of remote session attachment from a native application to to the (possibly suspended) extension. + */ + export function detach(): Promise; + export function detach(callback: (error?: string | undefined) => void): void; + /** Fires when a WebAuthn `navigator.credentials.create()` call occurs. The extension must supply a response by calling `completeCreateRequest()` with the `requestId` from `requestInfo`. */ + export const onCreateRequest: events.Event<(requestInfo: CreateRequest) => void>; + /** Fires when a WebAuthn `navigator.credentials.get()` call occurs. The extension must supply a response by calling `completeGetRequest()` with the `requestId` from `requestInfo` */ + export const onGetRequest: events.Event<(requestInfo: GetRequest) => void>; + /** Fires when a `PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()` call occurs. The extension must supply a response by calling `completeIsUvpaaRequest()` with the `requestId` from `requestInfo` */ + export const onIsUvpaaRequest: events.Event<(requestInfo: IsUvpaaRequest) => void>; + /** + * A native application associated with this extension can cause this event to be fired by writing to a file with a name equal to the extension's ID in a directory named `WebAuthenticationProxyRemoteSessionStateChange` inside the [default user data directory](https://chromium.googlesource.com/chromium/src/+/main/docs/user_data_dir.md#default-location) + * + * The contents of the file should be empty. I.e., it is not necessary to change the contents of the file in order to trigger this event. + * + * The native host application may use this event mechanism to signal a possible remote session state change (i.e. from detached to attached, or vice versa) while the extension service worker is possibly suspended. In the handler for this event, the extension can call the `attach()` or `detach()` API methods accordingly. + * + * The event listener must be registered synchronously at load time. + */ + export const onRemoteSessionStateChange: events.Event<() => void>; + /** Fires when a `onCreateRequest` or `onGetRequest` event is canceled (because the WebAuthn request was aborted by the caller, or because it timed out). When receiving this event, the extension should cancel processing of the corresponding request on the client side. Extensions cannot complete a request once it has been canceled. */ + export const onRequestCanceled: events.Event<(requestId: number) => void>; + } + + /** + * Use the `chrome.webNavigation` API to receive notifications about the status of navigation requests in-flight. * * Permissions: "webNavigation" */ @@ -12960,11 +14657,11 @@ export namespace Browser { /** A UUID of the document loaded. */ documentId: string; /** The lifecycle the document is in. */ - documentLifecycle: DocumentLifecycle; + 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: FrameType; + frameType: extensionTypes.FrameType; /** A UUID of the parent document owning this frame. This is not set if there is no parent. */ parentDocumentId?: string | undefined; /** ID of frame that wraps the frame. Set to -1 of no parent frame exists. */ @@ -13003,11 +14700,11 @@ export namespace Browser { /** 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. */ frameId: number; /** The type of frame the navigation occurred in. */ - frameType: FrameType; + 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: DocumentLifecycle; + documentLifecycle: extensionTypes.DocumentLifecycle; /** A UUID of the parent document owning this frame. This is not set if there is no parent. */ parentDocumentId?: string | undefined; /** @@ -13057,32 +14754,30 @@ export namespace Browser { export interface WebNavigationEventFilter { /** Conditions that the URL being navigated to must satisfy. The 'schemes' and 'ports' fields of UrlFilter are ignored for this event. */ - url: Browser.events.UrlFilter[]; + url: chrome.events.UrlFilter[]; } - export interface WebNavigationEvent - extends Browser.events.Event<(details: T) => void> - { + export interface WebNavigationEvent extends chrome.events.Event<(details: T) => void> { addListener(callback: (details: T) => void, filters?: WebNavigationEventFilter): void; } - export interface WebNavigationFramedEvent extends WebNavigationEvent {} + export interface WebNavigationFramedEvent extends WebNavigationEvent { + } - export interface WebNavigationFramedErrorEvent - extends WebNavigationEvent - {} + export interface WebNavigationFramedErrorEvent extends WebNavigationEvent { + } - export interface WebNavigationSourceEvent extends WebNavigationEvent {} + export interface WebNavigationSourceEvent extends WebNavigationEvent { + } - export interface WebNavigationParentedEvent extends WebNavigationEvent {} + export interface WebNavigationParentedEvent extends WebNavigationEvent { + } - export interface WebNavigationTransitionalEvent - extends WebNavigationEvent - {} + export interface WebNavigationTransitionalEvent extends WebNavigationEvent { + } - export interface WebNavigationReplacementEvent - extends WebNavigationEvent - {} + export interface WebNavigationReplacementEvent extends WebNavigationEvent { + } /** * Retrieves information about the given frame. A frame refers to an