### Basic Command Setup Source: https://developer.chrome.com/docs/extensions/reference/api/commands This example demonstrates the most basic setup for commands: declaring a command in the manifest and registering a listener in the service worker. ```json { "name": "Command demo - basic", "version": "1.0", "manifest_version": 3, "background": { "service_worker": "service-worker.js" }, "commands": { "inject-script": { "suggested_key": "Ctrl+Shift+Y", "description": "Inject a script on the page" } } } ``` ```javascript chrome.commands.onCommand.addListener((command) => { console.log(`Command "${command}" triggered`); }); ``` -------------------------------- ### Set an alarm on extension install Source: https://developer.chrome.com/docs/extensions/reference/alarms This example demonstrates how to create a repeating alarm with a delay when a new version of the extension is installed. The alarm is set to persist across sessions. ```javascript chrome.runtime.onInstalled.addListener(async ({ reason }) => { // Create an alarm so we have something to look at in the demo await chrome.alarms.create('demo-default-alarm', { delayInMinutes: 1, periodInMinutes: 1, persistAcrossSessions: true }); }); ``` -------------------------------- ### Listen for Extension Startup Source: https://developer.chrome.com/docs/extensions/reference/runtime Fired when a profile with this extension installed starts up. This event is not fired for incognito profiles. Use this for initialization tasks that should run when the browser starts. ```javascript chrome.runtime.onStartup.addListener( callback: function, ) ``` ```javascript () => void ``` -------------------------------- ### Manifest Example for Install Parameter Source: https://developer.chrome.com/docs/extensions/reference/manifest/chrome-settings-override This snippet demonstrates how to use the 'install_parameter' registry key to parametrize URL values in the manifest for external extensions. Occurrences of '__PARAM__' in URLs will be substituted with the 'install_parameter' value. ```json { "update_url": "https://clients2.google.com/service/update2/crx", "install_parameter": "Value" } ``` -------------------------------- ### GET /management/getAll Source: https://developer.chrome.com/docs/extensions/reference/api/management Retrieves a list of information about all installed extensions and applications. ```APIDOC ## GET /management/getAll ### Description Returns a list of information about installed extensions and apps. ### Method GET ### Endpoint chrome.management.getAll ### Parameters #### Path Parameters - None #### Query Parameters - None ### Request Example (No request body for GET request) ### Response #### Success Response (200) - **ExtensionInfo[]** - An array of `ExtensionInfo` objects for all installed extensions and apps. #### Response Example ```json [ { "id": "extension_id_1", "name": "Extension One", "version": "1.0", "installType": "normal", "enabled": true, "type": "extension" }, { "id": "app_id_1", "name": "App One", "version": "2.0", "installType": "development", "enabled": false, "type": "packaged_app" } ] ``` ``` -------------------------------- ### Set and Switch Side Panel Pages Source: https://developer.chrome.com/docs/extensions/reference/sidePanel Configure initial side panel pages on installation and dynamically switch between them based on tab activation. This example sets a welcome page initially and then switches to a main page when the user navigates to a different tab. ```javascript const welcomePage = 'sidepanels/welcome-sp.html'; const mainPage = 'sidepanels/main-sp.html'; chrome.runtime.onInstalled.addListener(() => { chrome.sidePanel.setOptions({ path: welcomePage }); chrome.sidePanel.setPanelBehavior({ openPanelOnActionClick: true }); }); chrome.tabs.onActivated.addListener(async ({ tabId }) => { const { path } = await chrome.sidePanel.getOptions({ tabId }); if (path === welcomePage) { chrome.sidePanel.setOptions({ path: mainPage }); } }); ``` -------------------------------- ### Listen for Profile Startup Source: https://developer.chrome.com/docs/extensions/reference/api/runtime Fired when a profile with this extension installed starts up. Not fired for incognito profiles. ```javascript chrome.runtime.onStartup.addListener( callback: function, ) ``` ```javascript () => void ``` -------------------------------- ### Node.js Project Setup Source: https://developer.chrome.com/docs/extensions/how-to/test/test-serviceworker-termination-with-puppeteer Sets up a Node.js project for Puppeteer testing with Jest. Includes necessary dependencies and a start script. ```json { "name": "puppeteer-demo", "version": "1.0", "dependencies": { "jest": "^29.7.0", "puppeteer": "^24.8.1" }, "scripts": { "start": "jest ." }, "devDependencies": { "@jest/globals": "^29.7.0" } } ``` -------------------------------- ### Handle Extension Installation and Updates Source: https://developer.chrome.com/docs/extensions/develop/concepts/service-workers/lifecycle Listen for the `onInstalled` event to perform one-time initialization tasks like creating context menus when an extension is installed or updated. ```javascript chrome.runtime.onInstalled.addListener((details) => { if(details.reason !== "install" && details.reason !== "update") return; chrome.contextMenus.create({ "id": "sampleContextMenu", "title": "Sample Context Menu", "contexts": ["selection"] }); }); ``` -------------------------------- ### chrome.management.getAll() Source: https://developer.chrome.com/docs/extensions/reference/management Gets a list of all installed extensions and apps. ```APIDOC ## chrome.management.getAll() ### Description Gets a list of all installed extensions and apps. ### Method `chrome.management.getAll(function callback)` ### Parameters #### Callback Function * **callback** (function) - Required - A callback function that is invoked with a list of `ExtensionInfo` objects. The callback function receives one argument: * **extensions** (`ExtensionInfo[]`) - A list of `ExtensionInfo` objects describing the installed extensions and apps. ``` -------------------------------- ### Example Scanner Options with Source and Resolution Source: https://developer.chrome.com/docs/extensions/reference/api/documentScan Provides a concrete example of scanner options, specifically showing 'source' and 'resolution' properties with their respective types and partial configurations. ```json { "source": { "name": "source", "type": OptionType.STRING, ... }, "resolution": { "name": "resolution", "type": OptionType.INT, ... }, ... ``` -------------------------------- ### chrome.management.installReplacementWebApp Source: https://developer.chrome.com/docs/extensions/reference/management Launches the replacement_web_app specified in the manifest. Prompts the user to install if not already installed. ```APIDOC ## chrome.management.installReplacementWebApp() ### Description Launches the replacement_web_app specified in the manifest. Prompts the user to install if not already installed. ### Method chrome.management.installReplacementWebApp ### Returns * Promise Chrome 88+ ``` -------------------------------- ### Valid Version Examples Source: https://developer.chrome.com/docs/extensions/reference/manifest/version These examples demonstrate valid formats for the 'version' field in the manifest. The integers must be between 0 and 65535, and non-zero integers cannot start with 0. The version cannot be all zeros. ```json "version": "1" ``` ```json "version": "1.0" ``` ```json "version": "2.10.2" ``` ```json "version": "3.1.2.4567" ``` -------------------------------- ### Install Replacement Web App Source: https://developer.chrome.com/docs/extensions/reference/api/management Launches the replacement_web_app specified in the manifest. Prompts the user to install if not already installed. Requires Chrome 77+ and returns a Promise in Chrome 88+. ```typescript chrome.management.installReplacementWebApp(): Promise ``` -------------------------------- ### Open Onboarding Page on Install Source: https://developer.chrome.com/docs/extensions/reference/api/tabs Opens an onboarding HTML page in a new tab when the Chrome extension is first installed. This is a common pattern for user onboarding. ```javascript chrome.runtime.onInstalled.addListener(({reason}) => { if (reason === 'install') { chrome.tabs.create({ url: "onboarding.html" }); } }); ``` -------------------------------- ### POST /management/installReplacementWebApp Source: https://developer.chrome.com/docs/extensions/reference/api/management Launches the replacement_web_app specified in the manifest. Prompts the user to install if not already installed. Available from Chrome 77+. ```APIDOC ## POST /management/installReplacementWebApp ### Description Launches the replacement_web_app specified in the manifest. Prompts the user to install if not already installed. ### Method POST ### Endpoint chrome.management.installReplacementWebApp ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body (No request body) ### Request Example (No request body) ### Response #### Success Response (200) - **None** (void) - Indicates successful execution. #### Response Example (No response body for void return type) ``` -------------------------------- ### Web Page Example Source: https://developer.chrome.com/docs/extensions/develop/concepts/content-scripts An example of a simple HTML page with a button and a script that adds an event listener. ```html ``` -------------------------------- ### Install Replacement Web App Source: https://developer.chrome.com/docs/extensions/reference/management Launches the replacement_web_app specified in the manifest, prompting the user for installation if it's not already installed. This method is available from Chrome 77+. ```javascript chrome.management.installReplacementWebApp(); ``` -------------------------------- ### Key Generation and Certificate Import Example Source: https://developer.chrome.com/docs/extensions/reference/api/enterprise/platformKeys An example demonstrating the typical workflow for generating a key pair, signing data, and importing a certificate using the chrome.enterprise.platformKeys API. ```APIDOC ### Request Example ```javascript function getUserToken(callback) { chrome.enterprise.platformKeys.getTokens(function(tokens) { for (var i = 0; i < tokens.length; i++) { if (tokens[i].id == "user") { callback(tokens[i]); return; } } callback(undefined); }); } function generateAndSign(userToken) { var data = new Uint8Array([0, 5, 1, 2, 3, 4, 5, 6]); var algorithm = { name: "RSASSA-PKCS1-v1_5", // RsaHashedKeyGenParams modulusLength: 2048, publicExponent: new Uint8Array([0x01, 0x00, 0x01]), // Equivalent to 65537 hash: { name: "SHA-256", } }; var cachedKeyPair; userToken.subtleCrypto.generateKey(algorithm, false, ["sign"]) .then(function(keyPair) { cachedKeyPair = keyPair; return userToken.subtleCrypto.exportKey("spki", keyPair.publicKey); }, console.log.bind(console)) .then(function(publicKeySpki) { // Build the Certification Request using the public key. return userToken.subtleCrypto.sign( {name : "RSASSA-PKCS1-v1_5"}, cachedKeyPair.privateKey, data); }, console.log.bind(console)) .then(function(signature) { // Complete the Certification Request with |signature|. // Send out the request to the CA, calling back // onClientCertificateReceived. }, console.log.bind(console)); } function onClientCertificateReceived(userToken, certificate) { chrome.enterprise.platformKeys.importCertificate(userToken.id, certificate); } getUserToken(generateAndSign); ``` ``` -------------------------------- ### Action Command Example Source: https://developer.chrome.com/docs/extensions/reference/api/commands This example shows how to map a command to trigger the extension's action, which then injects a content script. Note that the `_execute_action` command does not dispatch `onCommand` events. ```json { "name": "Commands demo - action invocation", "version": "1.0", "manifest_version": 3, "background": { "service_worker": "service-worker.js" }, "permissions": ["activeTab", "scripting"], "action": {}, "commands": { "_execute_action": { "suggested_key": { "default": "Ctrl+U", "mac": "Command+U" } } } } ``` ```javascript chrome.action.onClicked.addListener((tab) => { chrome.scripting.executeScript({ target: {tabId: tab.id}, func: contentScriptFunc, args: ['action'], }); }); function contentScriptFunc(name) { alert(`"${name}" executed`); } // This callback WILL NOT be called for "_execute_action" chrome.commands.onCommand.addListener((command) => { console.log(`Command "${command}" called`); }); ``` -------------------------------- ### Initialize Storage on Install Source: https://developer.chrome.com/docs/extensions/get-started/tutorial/service-worker-events Use the runtime.onInstalled event to set default values in chrome.storage.local when the extension is first installed. ```javascript chrome.runtime.onInstalled.addListener(({ reason }) => { if (reason === 'install') { chrome.storage.local.set({ apiSuggestions: ['tabs', 'storage', 'scripting'] }); } }); ``` -------------------------------- ### Include Globs Example 2 Source: https://developer.chrome.com/docs/extensions/reference/manifest/content-scripts This 'include_globs' example demonstrates matching URLs with a variable three-character string before 's' in the path. ```json { ... "content_scripts": [ { "matches": ["https://*.example.com/*"], "include_globs": ["*example.com/???s/*"], "js": ["content-script.js"] } ], ... } ``` -------------------------------- ### Linux: Personal Server Extension Installation Source: https://developer.chrome.com/docs/extensions/how-to/distribute/install-extensions Install an extension hosted on a personal server on Linux by pointing 'external_update_url' to an XML update file. Ensure the JSON file is world-readable. ```json { "external_update_url": "http://myhost.com/mytestextension/updates.xml" } ``` -------------------------------- ### chrome.storage.local.set() and get() Source: https://developer.chrome.com/docs/extensions/reference/storage Demonstrates setting and getting data from the local storage area. ```APIDOC ## chrome.storage.local.set() ### Description Sets one or more key/value pairs in the local storage area. ### Method `set(object items, function callback)` ### Parameters #### Arguments * **items** (object) - An object which is a map of key-value pairs to store. Use null to remove the value. * **callback** (function, optional) - Callback function for the request. ### Response #### Success Response No specific response body, but the callback is invoked upon completion. ## chrome.storage.local.get() ### Description Gets one or more items from the local storage area. ### Method `get(string or array of strings or object keys, function callback)` ### Parameters #### Arguments * **keys** (string or array of strings or object) - A single key or an array of keys to get the values for. Omit to get all key/value pairs. * **callback** (function) - Callback function with a map of key-value pairs. ### Response #### Success Response (200) * **object** - A map of key-value pairs. ### Request Example ```javascript await chrome.storage.local.set({ key: "value" }); console.log("Value is set"); const result = await chrome.storage.local.get(["key"]); console.log("Value is " + result.key); ``` ``` -------------------------------- ### Valid Version Name Examples Source: https://developer.chrome.com/docs/extensions/reference/manifest/version These examples show how to use the 'version_name' field for display purposes. This field can contain descriptive strings. ```json "version_name": "1.0 beta" ``` ```json "version_name": "build rc2" ``` ```json "version_name": "3.1.2.4567" ``` -------------------------------- ### Listen for Input Start Source: https://developer.chrome.com/docs/extensions/reference/api/omnibox The onInputStarted event fires when the user focuses the omnibox and starts typing. This can be used to prepare the extension for input. ```javascript chrome.omnibox.onInputStarted.addListener(() => { console.log('Input started'); }); ``` -------------------------------- ### Get All Installed Extensions Source: https://developer.chrome.com/docs/extensions/reference/management Retrieves a list of information about all installed extensions and apps on the browser. ```javascript chrome.management.getAll(); ``` -------------------------------- ### Get All Installed Extensions Source: https://developer.chrome.com/docs/extensions/reference/api/management Returns a list of information about all installed extensions and apps. Requires Chrome 88+. ```typescript chrome.management.getAll(): Promise ``` -------------------------------- ### Manifest Example for Homepage, Search Provider, and Startup Pages Source: https://developer.chrome.com/docs/extensions/reference/manifest/chrome-settings-override This snippet shows how to configure homepage, search provider, and startup pages in the extension manifest. Domain verification is required for any domain used in the settings API. ```json { "name": "My extension", ... "chrome_settings_overrides": { "homepage": "https://www.homepage.com", "search_provider": { "name": "name.__MSG_url_domain__", "keyword": "keyword.__MSG_url_domain__", "search_url": "https://www.foo.__MSG_url_domain__/s?q={searchTerms}", "favicon_url": "https://www.foo.__MSG_url_domain__/favicon.ico", "suggest_url": "https://www.foo.__MSG_url_domain__/suggest?q={searchTerms}", "instant_url": "https://www.foo.__MSG_url_domain__/instant?q={searchTerms}", "image_url": "https://www.foo.__MSG_url_domain__/image?q={searchTerms}", "search_url_post_params": "search_lang=__MSG_url_domain__", "suggest_url_post_params": "suggest_lang=__MSG_url_domain__", "instant_url_post_params": "instant_lang=__MSG_url_domain__", "image_url_post_params": "image_lang=__MSG_url_domain__", "alternate_urls": [ "https://www.moo.__MSG_url_domain__/s?q={searchTerms}", "https://www.noo.__MSG_url_domain__/s?q={searchTerms}" ], "encoding": "UTF-8", "is_default": true }, "startup_pages": ["https://www.startup.com"] }, "default_locale": "de", ... } ``` -------------------------------- ### chrome.management.get() Source: https://developer.chrome.com/docs/extensions/reference/management Gets information about the installed extension with the given ID. ```APIDOC ## chrome.management.get() ### Description Gets information about the installed extension with the given ID. ### Method `chrome.management.get(string id, function callback)` ### Parameters #### Path Parameters * **id** (string) - Required - The ID of the extension to retrieve. #### Callback Function * **callback** (function) - Required - A callback function that is invoked with an `ExtensionInfo` object describing the retrieved extension. The callback function receives one argument: * **extensionInfo** (`ExtensionInfo`) - Information about the extension. ``` -------------------------------- ### Build and Test a Simple Extension Source: https://developer.chrome.com/docs/extensions/ai/build_with_ai Use this prompt to have an AI agent build a basic extension with a popup and test it in the browser. The agent will automatically include necessary permissions like 'storage' for data persistence. ```prompt Build a simple "Quick notes" extension that opens a popup text area to save notes and test it in the browser. ``` -------------------------------- ### Listen for Bookmark Import Start Source: https://developer.chrome.com/docs/extensions/reference/api/bookmarks Fired when a bookmark import session begins. Useful for optimizing expensive observers. ```javascript chrome.bookmarks.onImportBegan.addListener( callback: function, ) ``` ```javascript () => void ``` -------------------------------- ### Get Font List Example Source: https://developer.chrome.com/docs/extensions/reference/api/fontSettings Retrieves a list of all available fonts. ```APIDOC ## getFontList() ### Description Gets a list of all available fonts. ### Response #### Success Response (200) - **fonts** (object) - An object where keys are font IDs and values are display names. ### Request Example ```javascript chrome.fontSettings.getFontList(function(fonts) { console.log(fonts); }); ``` ``` -------------------------------- ### Setup Test Entry Point Source: https://developer.chrome.com/docs/extensions/how-to/test/puppeteer Create an index.test.js file to serve as the entry point for your tests. Jest provides beforeEach and afterEach functions. ```javascript const puppeteer = require('puppeteer'); const EXTENSION_PATH = '../../api-samples/history/showHistory'; let browser; let worker; beforeEach(async () => { // TODO: Launch the browser. }); afterEach(async () => { // TODO: Close the browser. }); ``` -------------------------------- ### Get Minimum Font Size Example Source: https://developer.chrome.com/docs/extensions/reference/api/fontSettings Retrieves the minimum font size. ```APIDOC ## getMinimumFontSize() ### Description Gets the minimum font size. ### Response #### Success Response (200) - **fontSize** (integer) - The minimum font size. ### Request Example ```javascript chrome.fontSettings.getMinimumFontSize(function(size) { console.log(size); }); ``` ``` -------------------------------- ### Get Default Font Size Example Source: https://developer.chrome.com/docs/extensions/reference/api/fontSettings Retrieves the default font size. ```APIDOC ## getDefaultFontSize() ### Description Gets the default font size. ### Response #### Success Response (200) - **fontSize** (integer) - The default font size. ### Request Example ```javascript chrome.fontSettings.getDefaultFontSize(function(size) { console.log(size); }); ``` ``` -------------------------------- ### Show a popup Source: https://developer.chrome.com/docs/extensions/reference/api/action This example demonstrates how to configure an extension to display a popup when the user clicks the action icon. It involves setting the `default_popup` in the manifest. ```APIDOC ## Show a popup It's common for an extension to display a popup when the user clicks the extension's action. To implement this in your own extension, declare the popup in your `manifest.json` and specify the content that Chrome should display in the popup. ### Manifest Configuration ```json { "name": "Action popup demo", "version": "1.0", "manifest_version": 3, "action": { "default_title": "Click to view a popup", "default_popup": "popup.html" } } ``` ### Popup HTML Example ```html

Hello, world!

``` ``` -------------------------------- ### Scanner Options Structure Example Source: https://developer.chrome.com/docs/extensions/reference/api/documentScan Illustrates the general structure of the 'options' property within scanner configuration responses, showing key-value mappings of device-specific options. ```json { "key1": { scannerOptionInstance }, "key2": { scannerOptionInstance } } ``` -------------------------------- ### onInstalled Event Source: https://developer.chrome.com/docs/extensions/reference/management Fired when an app or extension has been installed. The listener receives an ExtensionInfo object. ```APIDOC ## onInstalled ### Description Fired when an app or extension has been installed. ### Method chrome.management.onInstalled.addListener ### Parameters #### Path Parameters * **callback** (function) - Required - The callback function to execute when the event is fired. It receives an `ExtensionInfo` object as an argument. ``` -------------------------------- ### GET /management/get Source: https://developer.chrome.com/docs/extensions/reference/api/management Retrieves information about an installed extension, app, or theme using its ID. ```APIDOC ## GET /management/get ### Description Returns information about the installed extension, app, or theme that has the given ID. ### Method GET ### Endpoint chrome.management.get ### Parameters #### Path Parameters - None #### Query Parameters - **id** (string) - Required - The ID from an item of `management.ExtensionInfo`. ### Request Example (No request body for GET request) ### Response #### Success Response (200) - **ExtensionInfo** - Information about the specified extension, app, or theme. #### Response Example ```json { "id": "extension_id_string", "name": "Example Extension", "version": "1.0", "installType": "normal", "enabled": true, "type": "extension" } ``` ``` -------------------------------- ### Get Font Example Source: https://developer.chrome.com/docs/extensions/reference/api/fontSettings Retrieves the font settings for a specified generic family and script. ```APIDOC ## getFont() ### Description Gets the font settings for a specified generic font family and script. ### Parameters #### Query Parameters - **genericFamily** (FontFamily) - Required - The generic font family. - **script** (ScriptCode) - Optional - The script code. ### Response #### Success Response (200) - **fontId** (string) - The font ID. - **displayName** (string) - The display name of the font. ### Request Example ```javascript chrome.fontSettings.getFont( { genericFamily: 'standard', script: 'Arab' }, function(details) { console.log(details.fontId); } ); ``` ``` -------------------------------- ### chrome.runtime.onStartup.addListener Source: https://developer.chrome.com/docs/extensions/reference/api/runtime Fired when a profile with the extension installed starts up. This event is not fired for incognito profiles. ```APIDOC ## chrome.runtime.onStartup.addListener ### Description Fired when a profile that has this extension installed first starts up. This event is not fired when an incognito profile is started, even if this extension is operating in 'split' incognito mode. ### Method addListener ### Parameters #### Callback Function - **callback** (function) - Required - The function to execute when the extension's profile starts up. It takes no arguments. ``` -------------------------------- ### Run Extension Update Testing Tool Source: https://developer.chrome.com/docs/extensions/develop/concepts/permission-warnings Instructions to start the local server for the Extension Update Testing Tool and access it in Chromium. ```bash npm start ``` -------------------------------- ### Get Default Fixed Font Size Example Source: https://developer.chrome.com/docs/extensions/reference/api/fontSettings Retrieves the default fixed font size. ```APIDOC ## getDefaultFixedFontSize() ### Description Gets the default fixed font size. ### Response #### Success Response (200) - **fontSize** (integer) - The default fixed font size. ### Request Example ```javascript chrome.fontSettings.getDefaultFixedFontSize(function(size) { console.log(size); }); ``` ``` -------------------------------- ### Get Extension Info by ID Source: https://developer.chrome.com/docs/extensions/reference/management Retrieves information about an installed extension, app, or theme using its ID. ```javascript chrome.management.get( "extensionId" ); ``` -------------------------------- ### Get Resource URL Source: https://developer.chrome.com/docs/extensions/reference/api/runtime Converts a relative path within the extension's install directory to a fully-qualified URL. ```javascript chrome.runtime.getURL("path"); ``` -------------------------------- ### chrome.runtime.onStartup.addListener Source: https://developer.chrome.com/docs/extensions/reference/runtime Fired when a profile with the extension installed starts up. This event is not fired for incognito profiles. It takes a callback function with no arguments. ```APIDOC ## chrome.runtime.onStartup.addListener ### Description Fired when a profile that has this extension installed first starts up. This event is not fired when an incognito profile is started, even if this extension is operating in 'split' incognito mode. ### Method chrome.runtime.onStartup.addListener ### Parameters #### callback - **callback** (function) - Required - The callback function to execute when the profile starts up. ### Callback Signature ```javascript () => void ``` ``` -------------------------------- ### Instantiate Language Model with Download Progress Source: https://developer.chrome.com/docs/extensions/ai/prompt-api Trigger the download of the language model and create a session. Listen for download progress to inform the user, as the download may take time. ```javascript const session = await LanguageModel.create({ monitor(m) { m.addEventListener('downloadprogress', (e) => { console.log(`Downloaded ${e.loaded * 100}%`); }); }, }); ``` -------------------------------- ### Get Bookmark Subtree Source: https://developer.chrome.com/docs/extensions/reference/api/bookmarks Retrieves a portion of the bookmark hierarchy starting from a specified node ID. Requires Chrome 90+. ```javascript chrome.bookmarks.getSubTree( id: string, ): Promise ``` -------------------------------- ### Get Extension Info by ID Source: https://developer.chrome.com/docs/extensions/reference/api/management Retrieves information about an installed extension, app, or theme using its ID. Requires Chrome 88+. ```typescript chrome.management.get(id: string): Promise ``` -------------------------------- ### Manifest File for Hello World Extension Source: https://developer.chrome.com/docs/extensions/get-started/tutorial/hello-world Defines the extension's name, description, version, manifest version, and action details like the popup and icon. ```json { "name": "Hello Extensions", "description": "Base Level Extension", "version": "1.0", "manifest_version": 3, "action": { "default_popup": "hello.html", "default_icon": "hello_extensions.png" } } ``` -------------------------------- ### Get Printer Information Source: https://developer.chrome.com/docs/extensions/reference/api/printing Fetches the status and capabilities of a printer in CDD format using its ID. This method may fail if the printer ID is not installed. ```javascript chrome.printing.getPrinterInfo( "printerId: string" ); ``` -------------------------------- ### Get Available Static Rule Count Source: https://developer.chrome.com/docs/extensions/reference/api/declarativeNetRequest Retrieve the number of available static rules at runtime. This is useful for understanding rule limits based on other installed extensions. ```javascript chrome.declarativeNetRequest.getAvailableStaticRuleCount().then(count => { console.log(`Available static rules: ${count}`); }); ``` -------------------------------- ### Install Extension Update Testing Tool Source: https://developer.chrome.com/docs/extensions/develop/concepts/permission-warnings Steps to set up the Extension Update Testing Tool, which requires Node.js, NPM, and Chromium. ```bash npm install ``` -------------------------------- ### Get Printer Information Source: https://developer.chrome.com/docs/extensions/reference/printing Fetches the capabilities and status of a printer in CDD format using its ID. The call fails if no printer with the specified ID is installed. Requires Chrome 100+. ```javascript chrome.printing.getPrinterInfo( printerId: string ): Promise ``` -------------------------------- ### Declarative Net Request Rule Prioritization Example Source: https://developer.chrome.com/docs/extensions/reference/api/declarativeNetRequest Illustrates Chrome's rule prioritization logic using 'priority', 'action', and 'urlFilter' keys. Requires host permission to '*://*.example.com/*'. ```json [ { "id": 1, "priority": 1, "action": { "type": "block" }, "condition": {"urlFilter": "||google.com/", "resourceTypes": ["main_frame"] } }, { "id": 2, "priority": 1, "action": { "type": "allow" }, "condition": { "urlFilter": "||google.com/123", "resourceTypes": ["main_frame"] } }, { "id": 3, "priority": 2, "action": { "type": "block" }, "condition": { "urlFilter": "||google.com/12345", "resourceTypes": ["main_frame"] } }, { "id": 4, "priority": 1, "action": { "type": "redirect", "redirect": { "url": "https://example.com" } }, "condition": { "urlFilter": "||google.com/", "resourceTypes": ["main_frame"] } }, ] ``` -------------------------------- ### CSP Error for Disallowed Source Source: https://developer.chrome.com/docs/extensions/reference/manifest/content-security-policy An example of an error message Chrome throws at install time if a disallowed source, such as 'unsafe-eval', is added to the 'script-src' directive within the 'extension_pages' policy. ```text 'content_security_policy.extension_pages': Insecure CSP value "'unsafe-eval'" in directive 'script-src'. ``` -------------------------------- ### Send a Prompt and Get a Response Source: https://developer.chrome.com/docs/extensions/ai/prompt-api Sends a prompt to the language model session and receives a response. This method can be used to continue a conversation or to guide the model's output with a prefix. ```APIDOC ## Send a Prompt and Get a Response ### Description Sends a prompt to the language model session and receives a response. This method can be used to continue a conversation or to guide the model's output with a prefix. ### Method `session.prompt()` ### Parameters #### Request Body - **prompts** (array) - Required - An array of prompt objects representing the conversation history or the current prompt. - **role** (string) - The role of the message ('user', 'assistant'). - **content** (string) - The content of the message. - **prefix** (boolean) - Optional - If true, this message is a prefix for the assistant's response. ### Request Example ```json { "prompts": [ { "role": "user", "content": "What is the capital of France?" }, { "role": "assistant", "content": "The capital of France is Paris.", "prefix": true } ] } ``` ### Response #### Success Response (response string) - **response** (string) - The response from the language model. ### Response Example ```json { "response": "The official language spoken in Paris is French." } ``` ``` -------------------------------- ### Start Tab Capture in Service Worker (Chrome 116+) Source: https://developer.chrome.com/docs/extensions/how-to/web-platform/screen-capture In a service worker, use chrome.tabCapture.getMediaStreamId() after a user gesture to get a stream ID for the active tab. This ID is then passed to an offscreen document for recording. ```javascript chrome.action.onClicked.addListener(async (tab) => { const existingContexts = await chrome.runtime.getContexts({}); const offscreenDocument = existingContexts.find( (c) => c.contextType === 'OFFSCREEN_DOCUMENT' ); // If an offscreen document is not already open, create one. if (!offscreenDocument) { // Create an offscreen document. await chrome.offscreen.createDocument({ url: 'offscreen.html', reasons: ['USER_MEDIA'], justification: 'Recording from chrome.tabCapture API', }); } // Get a MediaStream for the active tab. const streamId = await chrome.tabCapture.getMediaStreamId({ targetTabId: tab.id }); // Send the stream ID to the offscreen document to start recording. chrome.runtime.sendMessage({ type: 'start-recording', target: 'offscreen', data: streamId }); }); ``` -------------------------------- ### Get Side Panel Layout with `sidePanel.getLayout()` API Source: https://developer.chrome.com/docs/extensions/whats-new Starting in Chrome 140, use the `sidePanel.getLayout()` API to determine the side panel's position (left or right). This is useful for supporting RTL languages where the default position may differ. ```javascript chrome.sidePanel.getLayout().then(layout => { console.log(layout.position); // "left" or "right" }); ``` -------------------------------- ### Manifest Configuration for Side Panel Source: https://developer.chrome.com/docs/extensions/reference/sidePanel Example of how to configure the side panel in the extension's manifest file, including default path and permissions. ```APIDOC ## Manifest Configuration ### Permissions `sidePanel` To use the Side Panel API, add the `"sidePanel"` permission in the extension manifest file: ```json { "name": "My side panel extension", ... "permissions": [ "sidePanel" ] } ``` ### Default Path The side panel can be set initially from the `"default_path"` property in the `"side_panel"` key of the manifest to display the same side panel on every site. This should point to a relative path within the extension directory. ```json { "name": "My side panel extension", ... "side_panel": { "default_path": "sidepanel.html" } ... } ``` ``` -------------------------------- ### Listen for Install Language Requests Source: https://developer.chrome.com/docs/extensions/reference/api/ttsEngine Fired when a TTS client requests to install a new language. The engine should attempt to download and install the language, then call ttsEngine.updateLanguage and ttsEngine.updateVoices. ```javascript chrome.ttsEngine.onInstallLanguageRequest.addListener( callback: function, ) ``` -------------------------------- ### startCustomTouchCalibration() Source: https://developer.chrome.com/docs/extensions/reference/api/system/display Starts a custom touch calibration process for a display. This allows for a more tailored calibration experience. ```APIDOC ## POST /startCustomTouchCalibration ### Description Starts a custom touch calibration process for a display. ### Method POST ### Endpoint chrome.system.display.startCustomTouchCalibration(displayId, callback) ### Parameters #### Request Body - **displayId** (string) - Required - The unique identifier of the display for which to start custom touch calibration. #### Callback Function - **callback** (function) - Called when the custom touch calibration process has started. It takes no arguments. ### Response (No explicit response body defined for success, typically an empty response or success status) ### Error Handling - **Error**: If the display ID is invalid or the custom touch calibration cannot be started. ``` -------------------------------- ### get Source: https://developer.chrome.com/docs/extensions/reference/types Gets the value of a setting. This operation is asynchronous and returns a Promise. ```APIDOC ## get ### Description Gets the value of a setting. ### Method `get(details)` ### Parameters #### details - **details** (object) - Required - Specifies which setting to consider. - **incognito** (boolean) - Optional - Whether to return the value that applies to the incognito session (default false). ### Returns - **Promise** - Chrome 96+ - The value of the setting. ### Example ```javascript chrome.settings.get({ incognito: true }).then((value) => { console.log('Incognito setting value:', value); }); ``` ``` -------------------------------- ### onInputStarted Source: https://developer.chrome.com/docs/extensions/reference/api/omnibox User has started a keyword input session. ```APIDOC ## onInputStarted ### Description User has started a keyword input session. ### Method ``` chrome.omnibox.onInputStarted.addListener( callback: function ) ``` ### Parameters #### callback - **callback** (function) - The `callback` parameter looks like: ``` () => void ``` ``` -------------------------------- ### Set and get data from local storage Source: https://developer.chrome.com/docs/extensions/reference/api/storage Demonstrates how to set a key-value pair and then retrieve it using the local storage area. ```javascript await chrome.storage.local.set({ key: value }); console.log("Value is set"); const result = await chrome.storage.local.get(["key"]); console.log("Value is " + result.key); ``` -------------------------------- ### Example File Handler Configuration Source: https://developer.chrome.com/docs/extensions/reference/manifest/file-handlers This snippet shows how to configure the 'file_handlers' in the manifest to open plain text files with a specific HTML page. It defines the action, name, accepted MIME type and extensions, and launch type. ```json "file_handlers": [ { "action": "/open_text.html", "name": "Plain text", "accept": { "text/plain": [".txt"] } "launch_type": "single-client" } ] ``` -------------------------------- ### chrome.storage.session.set() and get() Source: https://developer.chrome.com/docs/extensions/reference/storage Demonstrates setting and getting data from the session storage area. ```APIDOC ## chrome.storage.session.set() ### Description Sets one or more key/value pairs in the session storage area. ### Method `set(object items, function callback)` ### Parameters #### Arguments * **items** (object) - An object which is a map of key-value pairs to store. Use null to remove the value. * **callback** (function, optional) - Callback function for the request. ### Response #### Success Response No specific response body, but the callback is invoked upon completion. ## chrome.storage.session.get() ### Description Gets one or more items from the session storage area. ### Method `get(string or array of strings or object keys, function callback)` ### Parameters #### Arguments * **keys** (string or array of strings or object) - A single key or an array of keys to get the values for. Omit to get all key/value pairs. * **callback** (function) - Callback function with a map of key-value pairs. ### Response #### Success Response (200) * **object** - A map of key-value pairs. ### Request Example ```javascript await chrome.storage.session.set({ key: "value" }); console.log("Value is set"); const result = await chrome.storage.session.get(["key"]); console.log("Value is " + result.key); ``` ``` -------------------------------- ### chrome.storage.sync.set() and get() Source: https://developer.chrome.com/docs/extensions/reference/storage Demonstrates setting and getting data from the sync storage area. ```APIDOC ## chrome.storage.sync.set() ### Description Sets one or more key/value pairs in the sync storage area. ### Method `set(object items, function callback)` ### Parameters #### Arguments * **items** (object) - An object which is a map of key-value pairs to store. Use null to remove the value. * **callback** (function, optional) - Callback function for the request. ### Response #### Success Response No specific response body, but the callback is invoked upon completion. ## chrome.storage.sync.get() ### Description Gets one or more items from the sync storage area. ### Method `get(string or array of strings or object keys, function callback)` ### Parameters #### Arguments * **keys** (string or array of strings or object) - A single key or an array of keys to get the values for. Omit to get all key/value pairs. * **callback** (function) - Callback function with a map of key-value pairs. ### Response #### Success Response (200) * **object** - A map of key-value pairs. ### Request Example ```javascript await chrome.storage.sync.set({ key: "value" }); console.log("Value is set"); const result = await chrome.storage.sync.get(["key"]); console.log("Value is " + result.key); ``` ``` -------------------------------- ### Gather feedback on uninstall Source: https://developer.chrome.com/docs/extensions/reference/api/runtime Example showing how to set an uninstall URL to gather feedback from users after they uninstall the extension. ```APIDOC ## Gather feedback on uninstall ### Description This example shows how to set an uninstall URL to gather feedback from users after they uninstall the extension. ### Background Script (`background.js`) ```javascript chrome.runtime.onInstalled.addListener(details => { if (details.reason === chrome.runtime.OnInstalledReason.INSTALL) { chrome.runtime.setUninstallURL('https://example.com/extension-survey'); } }); ``` ``` -------------------------------- ### HTML Structure for User Interface Source: https://developer.chrome.com/docs/extensions/how-to/integrate/oauth Sets up the basic HTML for the extension's user interface, including a button to trigger contact display and a div for content. ```html FriendBlock
``` -------------------------------- ### Create a Session with Initial Prompts Source: https://developer.chrome.com/docs/extensions/ai/prompt-api Initialize a session with a history of messages to provide context for the language model, enabling the resumption of stored conversations. ```javascript const session = await LanguageModel.create({ initialPrompts: [ { role: 'system', content: 'You are a helpful and friendly assistant.' }, { role: 'user', content: 'What is the capital of Italy?' }, { role: 'assistant', content: 'The capital of Italy is Rome.' }, { role: 'user', content: 'What language is spoken there?' }, { role: 'assistant', content: 'The official language of Italy is Italian. [...]', }, ], }); ``` -------------------------------- ### Get Tab Zoom Source: https://developer.chrome.com/docs/extensions/reference/api/tabs Gets the current zoom factor of a specified tab. ```APIDOC ## getZoom() ### Description Gets the current zoom factor of a specified tab. ### Method chrome.tabs.getZoom ### Parameters #### Path Parameters - **tabId** (number) - Optional - The ID of the tab to get the current zoom factor from; defaults to the active tab of the current window. #### Returns - **Promise** - Resolves with the tab's current zoom factor after it has been fetched. ``` -------------------------------- ### chrome.management.onInstalled Event Source: https://developer.chrome.com/docs/extensions/reference/api/management Fired when an app or extension is installed. Provides information about the installed item. ```APIDOC ## chrome.management.onInstalled ### Description Fired when an app or extension has been installed. ### Method `chrome.management.onInstalled.addListener(callback: function): void` ### Parameters #### Path Parameters - **callback** (function) - Required - The callback function to execute when the event is fired. It receives an `ExtensionInfo` object as an argument. - **info** (ExtensionInfo) - Information about the installed extension or app. ### Returns - void ``` -------------------------------- ### Setup and Create Offscreen Document Source: https://developer.chrome.com/docs/extensions/reference/api/offscreen Ensures an offscreen document exists by checking for an existing one or creating it. Avoids concurrency issues with a global promise. ```javascript let creating; async function setupOffscreenDocument(path) { const offscreenUrl = chrome.runtime.getURL(path); const existingContexts = await chrome.runtime.getContexts({ contextTypes: ['OFFSCREEN_DOCUMENT'], documentUrls: [offscreenUrl] }); if (existingContexts.length > 0) { return; } if (creating) { await creating; } else { creating = chrome.offscreen.createDocument({ url: path, reasons: ['CLIPBOARD'], justification: 'reason for needing the document', }); await creating; creating = null; } } ``` -------------------------------- ### Get Tab Zoom Settings Source: https://developer.chrome.com/docs/extensions/reference/api/tabs Gets the current zoom settings of a specified tab. ```APIDOC ## getZoomSettings() ### Description Gets the current zoom settings of a specified tab. ### Method chrome.tabs.getZoomSettings ### Parameters #### Path Parameters - **tabId** (number) - Optional - The ID of the tab to get the current zoom settings from; defaults to the active tab of the current window. #### Returns - **Promise** - Resolves with the tab's current zoom settings. ``` -------------------------------- ### HTML for Hello World Popup Source: https://developer.chrome.com/docs/extensions/get-started/tutorial/hello-world Creates the basic HTML structure for the extension's popup window. ```html

Hello Extensions

``` -------------------------------- ### get Source: https://developer.chrome.com/docs/extensions/reference/api/types Gets the value of a setting. This method allows you to retrieve the current value of a specified setting. ```APIDOC ## get ### Description Gets the value of a setting. ### Method `get(details: object) => Promise` ### Parameters #### details - **details** (object) - Required - Specifies which setting to consider. * **incognito** (boolean, optional) - Whether to return the value that applies to the incognito session. Defaults to false. ### Returns - **Promise** - Chrome 96+ - Returns an object containing the setting's value. ``` -------------------------------- ### Get all alarms Source: https://developer.chrome.com/docs/extensions/reference/alarms Gets an array of all the alarms. Returns a promise that resolves to an array of Alarm objects. ```javascript chrome.alarms.getAll(): Promise ```