### Basic Background Script Example Source: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Examples A simple background script that logs a message when the extension is installed. No specific setup is required beyond including it in the manifest. ```javascript browser.runtime.onInstalled.addListener(() => { console.log("Extension installed"); }); ``` -------------------------------- ### runtime.onInstalled Source: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/runtime Fired when the extension is first installed, or when the extension is updated to a new version. This event is commonly used to perform one-time setup tasks. ```APIDOC ## runtime.onInstalled ### Description Fired when the extension is first installed, or when the extension is updated to a new version. This event is commonly used to perform one-time setup tasks. ### Event `runtime.onInstalled` ### Parameters None. ### Event Listener Example ```javascript chrome.runtime.onInstalled.addListener((details) => { if (details.reason === 'install') { console.log('Extension installed!'); // Perform initial setup, e.g., create default settings } else if (details.reason === 'update') { console.log('Extension updated to version:', details.version); // Perform update-specific tasks } }); ``` ### Event Details The callback function receives an object with a `reason` property ('install', 'update', 'chrome_update', 'shared_module_update') and optionally a `version` property for updates. ``` -------------------------------- ### runtime.onStartup Source: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/runtime Fired when a profile that has this extension installed first starts up. This event is not fired when an incognito profile is started. ```APIDOC ## runtime.onStartup ### Description Fired when a profile that has this extension installed first starts up. This event is not fired when an incognito profile is started. ### Event runtime.onStartup ``` -------------------------------- ### runtime.onInstalled Source: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/runtime/onInstalled The `onInstalled` event is dispatched when the extension is first installed, updated to a new version, or when the browser itself is updated with the extension installed. This event is crucial for initializing extension states or performing one-time setup tasks. ```APIDOC ## runtime.onInstalled ### Description Fired when the extension is first installed, updated to a new version, or when the browser with an extension is updated to a new version. ### Event `runtime.onInstalled` ### Parameters This event does not have parameters that are directly exposed to the user for invocation. However, the event object associated with it contains information about the reason for installation or update. ### Example Usage ```javascript chrome.runtime.onInstalled.addListener((details) => { console.log('Extension installed or updated. Reason:', details.reason); // Perform one-time setup tasks here }); ``` ### Event Details - **reason** (OnInstalledReason) - The reason that the extension installed or updated. Possible values are: - `"install"`: The extension was installed. - ``"update"`: The extension was updated to a new version. - `"browser_update"`: The browser was updated to a new version. - `"shared_module_update"`: A shared module was updated. ``` -------------------------------- ### management Source: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API Get information about installed add-ons. ```APIDOC ## management ### Description Get information about installed add-ons. ### Method Not applicable (JavaScript API) ### Endpoint Not applicable (JavaScript API) ### Parameters Not applicable (JavaScript API) ### Request Example Not applicable (JavaScript API) ### Response Not applicable (JavaScript API) ``` -------------------------------- ### management.install() Source: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/management/ExtensionInfo Installs an extension from a given URL. ```APIDOC ## management.install() ### Description Installs an extension from a given URL. ### Method `management.install(url, options)` ### Parameters #### Path Parameters - **url** (string) - Required - The URL of the extension to install. - **options** (object) - Optional - An object for installation options. - **installSelf** (boolean) - Optional - If true, the extension is installed as a self-update. ### Response #### Success Response (200) - **ExtensionInfo** (object) - An object containing details about the newly installed extension. ### Response Example ```json { "id": "string", "version": "string", "name": "string", "enabled": "boolean", "installType": "string", "type": "string", "updateUrl": "string", "homepageUrl": "string", "mayDisable": "boolean", "hostPermissions": [ "string" ], "permissions": [ "string" ], "optionsUrl": "string", "icons": [ "string" ] } ``` ``` -------------------------------- ### Interacting with Browser Windows Source: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Examples Provides examples for creating new windows (`windows.create`), getting information about existing windows (`windows.getCurrent`, `windows.getAll`), updating window properties (`windows.update`), and closing windows (`windows.remove`). ```javascript // Create a new window browser.windows.create({ url: "about:blank", state: "normal" }); // Get current window info browser.windows.getCurrent().then(windowInfo => { console.log("Current window ID:", windowInfo.id); }); // Close a window browser.windows.remove(windowIdToClose); ``` -------------------------------- ### runtime.onStartup Event Source: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/runtime/onStartup Fired when a profile that has this extension installed first starts up. This event is not fired when a private browsing (incognito) profile is started, even if this extension is operating in 'split' incognito mode. ```APIDOC ## runtime.onStartup ### Description Fired when a profile that has this extension installed first starts up. This event is not fired when a private browsing (incognito) profile is started, even if this extension is operating in 'split' incognito mode. **Note:** When using an event page or background service worker, the extension must add a listener to `runtime.onStartup` on the event page for the event page to be executed at least once per browser session. ### Event Functions - `addListener(listener)`: Adds a `listener` to the calling event. - `removeListener(listener)`: Stop listening to the calling event. The `listener` argument is the listener to remove. - `hasListener(listener)`: Checks whether a `listener` is registered for the calling event. Returns `true` if it is listening, `false` otherwise. ### Parameters - `listener` (function): The function called when this event occurs. ``` -------------------------------- ### Log target URLs for onCompleted Source: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/webNavigation/onCompleted This example logs the target URLs for the onCompleted event, but only if the URL's hostname contains 'example.com' or starts with 'developer'. ```javascript function logExampleAndDeveloper(details) { console.log("Navigation completed to: " + details.url); } browser.webNavigation.onCompleted.addListener( logExampleAndDeveloper, {url: [{hostContains: "example.com"}, {hostnamePrefix: "developer"}]} ); ``` -------------------------------- ### management.getAll() Source: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/management/ExtensionInfo Retrieves information about all installed extensions. ```APIDOC ## management.getAll() ### Description Retrieves information about all installed extensions. ### Method `management.getAll()` ### Response #### Success Response (200) - **ExtensionInfo array** (array) - An array of objects, where each object contains details about an installed extension. ### Response Example ```json [ { "id": "string", "version": "string", "name": "string", "enabled": "boolean", "installType": "string", "type": "string", "updateUrl": "string", "homepageUrl": "string", "mayDisable": "boolean", "hostPermissions": [ "string" ], "permissions": [ "string" ], "optionsUrl": "string", "icons": [ "string" ] } ] ``` ``` -------------------------------- ### messages.json Example Source: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/i18n/Locale-Specific_Message_reference An example messages.json file demonstrating the required '_name_' and 'message' fields, along with optional 'description' and 'placeholders'. ```json { "extensionName": { "message": "Notify Link Clicks", "description": "The name of the extension." }, "notificationTitle": { "message": "Link Clicked!", "description": "The title of the notification that appears." }, "notificationContent": { "message": "You clicked on $URL$ which opened a new tab.", "description": "The content of the notification. $URL$ will be replaced with the URL that was clicked.", "placeholders": { "URL": { "content": "$1", "example": "https://www.mozilla.org" } } } } ``` -------------------------------- ### Manifest V3 CSP Example Source: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/content_security_policy This example demonstrates the structure for specifying content security policies in Manifest V3, separating policies for extension pages and sandboxed pages. ```json { "manifest_version": 3, "name": "My extension", "version": "0.1", "content_security_policy": { "extension_pages": "script-src 'self'; object-src 'none'", "sandbox": "script-src 'self' 'wasm-unsafe-eval'; object-src 'none'" } } ``` -------------------------------- ### Example of using the 'browser' namespace Source: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Differences_between_API_implementations This example shows how to reference an API function using the 'browser' namespace, commonly used in Firefox and Safari. ```javascript browser.alarms.create({delayInMinutes}); ``` -------------------------------- ### Manifest V2 CSP Example Source: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/content_security_policy This example shows how to specify a content security policy for Manifest V2. It allows scripts from the extension's own package and from external HTTPS sources. ```json { "manifest_version": 2, "name": "My extension", "version": "0.1", "content_security_policy": "script-src 'self' https://example.com; object-src 'none'" } ``` -------------------------------- ### Basic `windows.create` Example Source: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Examples Opens a new browser window using `windows.create`. You can specify properties like the URL to open, window state (normal, maximized, etc.), and dimensions. The result is a promise resolving to a `Window` object. ```javascript browser.windows.create({ url: "https://www.example.com", state: "maximized" }); ``` -------------------------------- ### Basic `runtime.openOptionsPage` Example Source: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Examples Opens the extension's options page using `runtime.openOptionsPage`. This is typically called from a popup or context menu item to allow users to configure the extension. ```javascript browser.runtime.openOptionsPage(); ``` -------------------------------- ### Get all cookies with a specific name Source: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/cookies/getAll This example gets all of the cookies the browser has stored with the name "favorite-color". When the result is returned, the code prints the value of each result to the console. ```javascript async function getAllCookies() { const allCookies = await browser.cookies.getAll({ name: "favorite-color" }); for (const cookie of allCookies) { console.log(cookie.value); } } ``` -------------------------------- ### Initialize Extension on Install Source: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Background_scripts Listens for the `runtime.onInstalled` event to perform one-time initialization tasks for an extension, such as setting initial state or creating context menus. ```javascript chrome.runtime.onInstalled.addListener(() => { console.log('Extension installed'); // Example: Create a context menu item chrome.contextMenus.create({ id: "myContextMenu", title: "My Context Menu Item", contexts: ["page", "selection", "image", "link"] }); }); ``` -------------------------------- ### Set multiple icons using paths Source: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/browserAction/setIcon This example shows how to specify multiple icon files in different sizes using a dictionary object for the path. ```javascript chrome.browserAction.setIcon({ path: { "16": "icons/icon16.png", "32": "icons/icon32.png", "48": "icons/icon48.png", "128": "icons/icon128.png" } }); ``` -------------------------------- ### Get URL for a resource Source: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/extension/getURL Use this to get the full URL for a file packaged with the add-on. The path is relative to the extension's install directory. This function is deprecated; use runtime.getURL() instead. ```javascript let url = extension.getURL("beasts/frog.html"); console.log(url); ``` -------------------------------- ### Version Comparison Examples Source: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/version/format Demonstrates various version string comparisons, highlighting equality and inequality based on version part ordering and parsing rules. ```text 1.-1 < 1 == 1. == 1.0 == 1.0.0 < 1.1a < 1.1aa < 1.1ab < 1.1b < 1.1c < 1.1pre == 1.1pre0 == 1.0+ < 1.1pre1a < 1.1pre1aa < 1.1pre1b < 1.1pre1 < 1.1pre2 < 1.1pre10 < 1.1.-1 < 1.1 == 1.1.0 == 1.1.00 < 1.10 < 1.* < 1.*.1 < 2.0 ``` -------------------------------- ### management.install() Source: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/management Installs a theme from a given URL. This function requires the 'management' API permission. ```APIDOC ## management.install() ### Description Installs a particular theme, given its URL at addons.mozilla.org. ### Method `management.install(url)` ### Parameters #### Path Parameters - **url** (string) - Required - The URL of the theme to install from addons.mozilla.org. ### Response - **extensionInfo** (`management.ExtensionInfo`): An object containing information about the newly installed theme. ### Request Example ```javascript const themeUrl = 'https://addons.mozilla.org/theme/example-theme'; management.install(themeUrl).then(extensionInfo => { console.log('Theme installed:', extensionInfo); }); ``` ### Response Example ```json { "id": "theme_id_1", "name": "Example Theme", "version": "1.0", "enabled": true // ... other ExtensionInfo properties } ``` ``` -------------------------------- ### management.get() Source: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/management/onInstalled Gets information about a specific installed extension. You can use the extension's ID to retrieve its details. ```APIDOC ## management.get() ### Description Gets information about a specific installed extension. ### Parameters #### Query Parameters - **extensionId** (string) - Required - The ID of the extension to retrieve information for. ``` -------------------------------- ### Open Options Page Source: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/runtime/openOptionsPage This example demonstrates how to open the extension's options page, typically called from a button click or another user interaction within the extension. ```APIDOC ## runtime.openOptionsPage() ### Description Opens the extension's options page. ### Method `runtime.openOptionsPage()` ### Parameters This method does not accept any parameters. ### Example ```javascript // Opens the extension's options page function openOptions() { browser.runtime.openOptionsPage(); } // Example usage: Attach to a button click document.getElementById('options-button').addEventListener('click', openOptions); ``` ### Response This method does not return a value directly. It initiates the opening of the options page. Errors, such as the options page not being defined in the manifest, may be reported via `runtime.lastError`. ``` -------------------------------- ### Get Zoom Settings Source: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs/getZoomSettings This example shows how to retrieve the zoom settings for the current tab using the `tabs.getZoomSettings()` method. ```APIDOC ## GET /tabs/getZoomSettings ### Description Retrieves the zoom settings for the current tab. ### Method GET ### Endpoint `tabs.getZoomSettings()` ### Parameters This method does not take any parameters. ### Response #### Success Response (200) - **zoomSettings** (object) - An object containing the zoom settings. - **mode** (string) - The zoom mode ('automatic', 'manual', 'disabled'). - **scope** (string) - The scope of the zoom settings ('per-tab', 'per-origin'). - **defaultZoom** (number) - The default zoom factor. #### Response Example ```json { "mode": "automatic", "scope": "per-tab", "defaultZoom": 1.0 } ``` ``` -------------------------------- ### management.getPermissionWarningsByManifest() Source: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/management/onInstalled Gets permission warnings for an extension based on its manifest data. This method is useful for validating permissions before installation. ```APIDOC ## management.getPermissionWarningsByManifest() ### Description Gets permission warnings for an extension based on its manifest data. ### Parameters #### Request Body - **manifest** (object) - Required - The manifest object of the extension. ``` -------------------------------- ### windows.create() Source: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/windows Creates a new window. ```APIDOC ## windows.create() ### Description Creates a new window. ### Method (Not specified in source) ### Endpoint (Not specified in source) ### Parameters #### Request Body * **options** (windows.CreateType) - Optional - Properties to set on the new window. ### Response #### Success Response (200) * **window** (windows.Window) - The newly created window. #### Response Example (Not specified in source) ``` -------------------------------- ### bookmarks.getSubTree() Source: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/bookmarks/getSubTree Retrieves a subtree of the bookmark hierarchy. You can specify a starting node ID to get a specific branch of bookmarks and their children. ```APIDOC ## bookmarks.getSubTree() ### Description Retrieves a subtree of the bookmark hierarchy, starting from a specified node. ### Method `bookmarks.getSubTree(id, callback)` ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the node from which to retrieve the subtree. Use 'root------' for the root. #### Callback Function - **callback** (function) - Required - A function that will be called with the result. - **result** (array of BookmarkTreeNode) - An array containing the BookmarkTreeNode objects representing the subtree. ### Example ```javascript function getBookmarkSubTree(callback) { bookmarks.getSubTree('root------', function(result) { callback(result); }); } ``` ``` -------------------------------- ### management.install() Source: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/management/install Installs and enables a theme extension from the given URL. This API requires the "management" API permission and will only work with signed themes. It is an asynchronous function that returns a Promise. ```APIDOC ## management.install() ### Description Installs and enables a theme extension from the given URL. ### Method POST (implied, as it's an installation action) ### Endpoint management/install ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **options** (object) - Required - An object that includes the URL of the XPI file of the theme at addons.mozilla.org and an optional a hash of the XPI file, using sha256 or stronger. - **url** (string) - Required - The URL of the XPI file. - **hash** (string) - Optional - The SHA256 hash of the XPI file. ### Request Example ```json { "options": { "url": "https://addons.mozilla.org/firefox/downloads/file/123456/my-theme.xpi", "hash": "sha256:abcdef1234567890..." } } ``` ### Response #### Success Response (200) - **ExtensionID** (string) - The ID of the installed extension. #### Response Example ```json { "ExtensionID": "my-theme@example.com" } ``` ``` -------------------------------- ### management.getPermissionWarningsById() Source: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/management/getPermissionWarningsById Use the `management.getPermissionWarningsById()` method to get permission warnings for an extension. This is useful for informing users about the permissions an extension requires before or during installation. ```APIDOC ## management.getPermissionWarningsById() ### Description Retrieves permission warnings for a given extension ID. ### Method `management.getPermissionWarningsById(extensionId)` ### Parameters #### Path Parameters - **extensionId** (string) - Required - The ID of the extension to retrieve warnings for. ### Response #### Success Response (Array of strings) - Returns an array of strings, where each string is a permission warning message. #### Response Example ```json [ "Access your data for all websites", "Read and change your browsing history" ] ``` ``` -------------------------------- ### Controlling Downloads Source: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Examples Includes examples for handling download events (`downloads.onCreated`), searching for downloads (`downloads.search`), and controlling download states like pausing (`downloads.pause`), resuming (`downloads.resume`), and canceling (`downloads.cancel`). ```javascript // Pause a download browser.downloads.pause(downloadIdToPause); // Resume a download browser.downloads.resume(downloadIdToResume); // Cancel a download browser.downloads.cancel(downloadIdToCancel); ``` -------------------------------- ### Registering an Event Listener Source: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Background_scripts Listeners must be registered synchronously from the start of the page. This example shows the correct way to register a listener for runtime messages. ```javascript browser.runtime.onMessage.addListener(listener); ``` -------------------------------- ### Basic manifest.json structure Source: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json This example shows the basic syntax for common manifest keys. It is not intended for direct use but illustrates the structure and common fields. ```json { "manifest_version": 3, "name": "My extension", "version": "1.0", "description": "The description of my extension.", "icons": { "48": "icons/border-48.png" }, "permissions": [ "storage" ], "background": { "scripts": ["background.js"] }, "content_scripts": [ { "matches": ["*://*.example.com/*"], "js": ["content-script.js"] } ], "browser_action": { "default_icon": "icons/border-48.png", "default_title": "Click me!", "default_popup": "popup.html" } } ``` -------------------------------- ### runtime.onInstalled Source: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/runtime 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. ```APIDOC ## runtime.onInstalled ### Description 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. ### Event runtime.onInstalled ``` -------------------------------- ### runtime.onUpdateAvailable Source: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/runtime/onUpdateAvailable This event is fired when an update is available for the extension. It allows the extension to react to the update being available, for example, by notifying the user that a new version can be installed. ```APIDOC ## runtime.onUpdateAvailable ### Description Fired when an update is available for the extension. This event is only sent to the background script of the extension. It is not fired if the extension is already running the latest version. ### Event Signature `chrome.runtime.onUpdateAvailable.addListener(callback)` ### Parameters * **callback** (function) * A function that will be called when the `onUpdateAvailable` event is fired. The function will be passed an object with details about the update. ### Callback Parameters * **details** (object) * An object containing details about the update. * **version** (string) - The new version of the extension that is available. ``` -------------------------------- ### Content Script Load Order Example Source: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/content_scripts Illustrates the order in which content scripts and CSS files are loaded based on 'run_at' and array order. ```json { "content_scripts": [ { "matches": ["*://*.mozilla.org/*"], "css": ["my-css.css"], "js": ["jquery.js", "my-content-script.js"], "run_at": "document_idle" }, { "matches": ["*://*.mozilla.org/*"], "js": ["another-content-script.js", "yet-another-content-script.js"], "run_at": "document_idle" } ] } ``` -------------------------------- ### Load two background scripts Source: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/background This example demonstrates how to load two background scripts for an extension. ```json { "manifest_version": 2, "name": "My App", "version": "0.1", "background": { "scripts": ["background.js", "background2.js"] } } ``` -------------------------------- ### Toggle allowPopupsForUserEvents Source: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/browserSettings/allowPopupsForUserEvents This example demonstrates how to get the current value of the `allowPopupsForUserEvents` setting and then toggle it. It also includes an event listener to log changes to the setting. ```javascript async function toggleAllowPopups() { const enabled = await browser.browserSettings.allowPopupsForUserEvents.get({}); await browser.browserSettings.allowPopupsForUserEvents.set({ value: !enabled }); console.log(`allowPopupsForUserEvents is now: ${!enabled}`); } toggleAllowPopups(); browser.browserSettings.allowPopupsForUserEvents.onChange.addListener(details => { console.log("allowPopupsForUserEvents changed:", details.value); }); ``` -------------------------------- ### Using rangeData to Get Match Context Source: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/find/find Retrieves the context of a match using rangeData, which provides the text content of the node where the match was found. This example does not handle frames. ```javascript // Background script: await browser.find.find("banana"); const matches = await browser.find.getRangeData(); console.log(matches); ``` ```javascript // Content script: console.log("Content script executed."); ``` -------------------------------- ### commands.openShortcutSettings() Source: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/commands/Command Opens the extension's shortcut settings page. ```APIDOC ## commands.openShortcutSettings() ### Description Opens the extension's shortcut settings page in the browser. ### Method `commands.openShortcutSettings()` ``` -------------------------------- ### Getting Browser Information Source: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Examples Provides an example of retrieving information about the browser environment using `runtime.getBrowserInfo`. This includes the browser's name, version, and operating system, which can be useful for compatibility checks or logging. ```javascript browser.runtime.getBrowserInfo().then(info => { console.log(`Running on ${info.name} ${info.version} (${info.os})`); }); ``` -------------------------------- ### Managing Extension Settings with `storage.sync` Source: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Examples Illustrates using `storage.sync` for settings that should be synchronized across multiple browser instances signed into the same account. This is ideal for user preferences that need to be consistent everywhere. ```javascript // Save a setting browser.storage.sync.set({ "syncEnabled": true }); // Retrieve a setting browser.storage.sync.get("syncEnabled").then(result => { console.log(`Sync enabled: ${result.syncEnabled}`); }); // Remove a setting browser.storage.sync.remove("syncEnabled"); // Clear all sync storage browser.storage.sync.clear(); ``` -------------------------------- ### Getting the Extension ID with `runtime.id` Source: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Examples Accesses the unique ID of the currently running extension via `runtime.id`. This ID is assigned when the extension is installed and is useful for constructing URLs or identifying the extension in logs. ```javascript const extensionId = browser.runtime.id; console.log(`Extension ID: ${extensionId}`); ``` -------------------------------- ### Log history state updates for specific URLs Source: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/webNavigation/onHistoryStateUpdated This example demonstrates how to use the onHistoryStateUpdated event to log navigation details. It filters events to only include those where the target URL's hostname contains 'example.com' or starts with 'developer'. ```javascript browser.webNavigation.onHistoryStateUpdated.addListener( (details) => { console.log(`History state updated: ${details.url}`); if (details.transitionQualifiers) { console.log(` Transition qualifiers: ${details.transitionQualifiers.join(', ')}`); } if (details.transitionType) { console.log(` Transition type: ${details.transitionType}`); } }, { url: [ { hostnameContains: 'example.com' }, { hostnamePrefix: 'developer' } ] } ); ``` -------------------------------- ### Register a simple hello world user script Source: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/userScripts/register This snippet registers a 'hello world' script into the 'myScriptId' execution world. It is configured to run on all websites matching the pattern '*://example.com/*'. Ensure the 'js' property is a non-empty array and either 'matches' or 'includeGlobs' is also provided. ```javascript await userScripts.register([ { "id": "myScriptId", "js": [{"code": "console.log('Hello world!');"}], "matches": ["*://example.com/*"] } ]); ``` -------------------------------- ### Getting All Tabs with `tabs.query` Source: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Examples Queries for tabs that match specified criteria using `tabs.query`. This is a powerful way to find specific tabs, for example, all tabs in a certain window or with a particular URL. The `query` object specifies the matching conditions. ```javascript browser.tabs.query({ active: true, // Get the active tab currentWindow: true // In the current window }).then(tabs => { if (tabs.length > 0) { console.log("Active tab title:", tabs[0].title); } }); ``` -------------------------------- ### Extension File Structure Example Source: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Extension_pages Illustrates how to include HTML, CSS, and JavaScript files within an extension's directory structure. Files can be placed in the root or organized into sub-folders. ```text /my-extension /manifest.json /my-page.html /my-page.js ``` -------------------------------- ### runtime.onStartup Source: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/runtime Fired when the browser is first launched. This event is useful for initializing extension components or loading settings when the browser starts. ```APIDOC ## runtime.onStartup ### Description Fired when the browser is first launched. This event is useful for initializing extension components or loading settings when the browser starts. ### Event `runtime.onStartup` ### Parameters None. ### Event Listener Example ```javascript chrome.runtime.onStartup.addListener(() => { console.log('Browser started. Initializing extension...'); // Load settings, initialize services, etc. }); ``` ### Event Details This event does not provide any specific data in its callback. ``` -------------------------------- ### Update menu item with link hostname Source: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/menus/onShown This example demonstrates how to listen for the context menu being shown over a link and update a specific menu item with the link's hostname. It utilizes menus.onShown to get context and menus.refresh() to apply the changes. ```javascript menus.onShown.addListener((info) => { if (info.linkURL) { menus.refresh({ openLabelId: "open-labelled-id", label: "Open " + new URL(info.linkURL).hostname }); } }); ``` -------------------------------- ### Get and remove context menu target element Source: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/menus/getTargetElement This example demonstrates how to use menus.getTargetElement() to retrieve the element that triggered a context menu and then remove it from the DOM. It requires the 'menus' permission and must be called within the same document context as the element. ```javascript browser.menus.onClicked.addListener((info, tab) => { if (info.menuItemId === "remove-element") { const element = menus.getTargetElement(info.targetElementId); if (element) { element.remove(); } } }); ``` -------------------------------- ### Listening for `runtime.onMessage` Source: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Examples Example of setting up a listener for messages sent from other parts of the extension (e.g., content scripts or popups) using `runtime.onMessage`. The listener receives the message data and sender information. ```javascript browser.runtime.onMessage.addListener((message, sender, sendResponse) => { if (message.action === "getData") { sendResponse({ data: "some data from background" }); } }); ``` -------------------------------- ### management.onInstalled Source: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/management/onInstalled Fired when an add-on is installed. This event provides information about the newly installed add-on. ```APIDOC ## management.onInstalled() ### Description Fired when an add-on is installed. This event allows you to react to the installation of an add-on and retrieve details about it. ### Syntax `management.onInstalled.addListener(listener)` `management.onInstalled.removeListener(listener)` `management.onInstalled.hasListener(listener)` ### Parameters #### addListener(listener) * **listener** (`function`) * The callback function to execute when the event is fired. * This function receives one argument: * **info** (`ExtensionInfo`) * An object containing information about the installed add-on. ``` -------------------------------- ### Proxy Request Example Source: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/proxy/onRequest Intercepts requests to all URLs and proxies them if they are not for a top-level frame. This example demonstrates returning a ProxyInfo object. ```javascript function logURL(requestDetails) { console.log("proxying:", requestDetails.url); return { type: "http", host: "127.0.0.1", port: 3000 }; } browser.proxy.onRequest.addListener(logURL, { urls: [""] }, ["requestHeaders"]); ``` -------------------------------- ### Load a custom background page Source: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/background This example shows how to load a custom HTML page as the background for an extension. ```json { "manifest_version": 2, "name": "My App", "version": "0.1", "background": { "page": "background.html" } } ```