{ // 获取包含Hugging Face文本的span元素 const spans = link.querySelectorAll('span.whitespace-nowrap, span.hidden.whitespace-nowrap'); spans.forEach(span => { if (span.textContent && span.textContent.trim().match(/Hugging\s*Face/i)) { span.textContent = 'AI快站'; } }); }); // 替换logo图片的alt属性 document.querySelectorAll('img[alt*="Hugging"], img[alt*="Face"]').forEach(img => { if (img.alt.match(/Hugging\s*Face/i)) { img.alt = 'AI快站 logo'; } }); } // 替换导航栏中的链接 function replaceNavigationLinks() { // 已替换标记,防止重复运行 if (window._navLinksReplaced) { return; } // 已经替换过的链接集合,防止重复替换 const replacedLinks = new Set(); // 只在导航栏区域查找和替换链接 const headerArea = document.querySelector('header') || document.querySelector('nav'); if (!headerArea) { return; } // 在导航区域内查找链接 const navLinks = headerArea.querySelectorAll('a'); navLinks.forEach(link => { // 如果已经替换过,跳过 if (replacedLinks.has(link)) return; const linkText = link.textContent.trim(); const linkHref = link.getAttribute('href') || ''; // 替换Spaces链接 - 仅替换一次 if ( (linkHref.includes('/spaces') || linkHref === '/spaces' || linkText === 'Spaces' || linkText.match(/^s*Spacess*$/i)) && linkText !== 'OCR模型免费转Markdown' && linkText !== 'OCR模型免费转Markdown' ) { link.textContent = 'OCR模型免费转Markdown'; link.href = 'https://fast360.xyz'; link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener noreferrer'); replacedLinks.add(link); } // 删除Posts链接 else if ( (linkHref.includes('/posts') || linkHref === '/posts' || linkText === 'Posts' || linkText.match(/^s*Postss*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } // 替换Docs链接 - 仅替换一次 else if ( (linkHref.includes('/docs') || linkHref === '/docs' || linkText === 'Docs' || linkText.match(/^s*Docss*$/i)) && linkText !== '模型下载攻略' ) { link.textContent = '模型下载攻略'; link.href = '/'; replacedLinks.add(link); } // 删除Enterprise链接 else if ( (linkHref.includes('/enterprise') || linkHref === '/enterprise' || linkText === 'Enterprise' || linkText.match(/^s*Enterprises*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } }); // 查找可能嵌套的Spaces和Posts文本 const textNodes = []; function findTextNodes(element) { if (element.nodeType === Node.TEXT_NODE) { const text = element.textContent.trim(); if (text === 'Spaces' || text === 'Posts' || text === 'Enterprise') { textNodes.push(element); } } else { for (const child of element.childNodes) { findTextNodes(child); } } } // 只在导航区域内查找文本节点 findTextNodes(headerArea); // 替换找到的文本节点 textNodes.forEach(node => { const text = node.textContent.trim(); if (text === 'Spaces') { node.textContent = node.textContent.replace(/Spaces/g, 'OCR模型免费转Markdown'); } else if (text === 'Posts') { // 删除Posts文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } else if (text === 'Enterprise') { // 删除Enterprise文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } }); // 标记已替换完成 window._navLinksReplaced = true; } // 替换代码区域中的域名 function replaceCodeDomains() { // 特别处理span.hljs-string和span.njs-string元素 document.querySelectorAll('span.hljs-string, span.njs-string, span[class*="hljs-string"], span[class*="njs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换hljs-string类的span中的域名(移除多余的转义符号) document.querySelectorAll('span.hljs-string, span[class*="hljs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换pre和code标签中包含git clone命令的域名 document.querySelectorAll('pre, code').forEach(element => { if (element.textContent && element.textContent.includes('git clone')) { const text = element.innerHTML; if (text.includes('huggingface.co')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 处理特定的命令行示例 document.querySelectorAll('pre, code').forEach(element => { const text = element.innerHTML; if (text.includes('huggingface.co')) { // 针对git clone命令的专门处理 if (text.includes('git clone') || text.includes('GIT_LFS_SKIP_SMUDGE=1')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 特别处理模型下载页面上的代码片段 document.querySelectorAll('.flex.border-t, .svelte_hydrator, .inline-block').forEach(container => { const content = container.innerHTML; if (content && content.includes('huggingface.co')) { container.innerHTML = content.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 特别处理模型仓库克隆对话框中的代码片段 try { // 查找包含"Clone this model repository"标题的对话框 const cloneDialog = document.querySelector('.svelte_hydration_boundary, [data-target="MainHeader"]'); if (cloneDialog) { // 查找对话框中所有的代码片段和命令示例 const codeElements = cloneDialog.querySelectorAll('pre, code, span'); codeElements.forEach(element => { if (element.textContent && element.textContent.includes('huggingface.co')) { if (element.innerHTML.includes('huggingface.co')) { element.innerHTML = element.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { element.textContent = element.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); } // 更精确地定位克隆命令中的域名 document.querySelectorAll('[data-target]').forEach(container => { const codeBlocks = container.querySelectorAll('pre, code, span.hljs-string'); codeBlocks.forEach(block => { if (block.textContent && block.textContent.includes('huggingface.co')) { if (block.innerHTML.includes('huggingface.co')) { block.innerHTML = block.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { block.textContent = block.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); }); } catch (e) { // 错误处理但不打印日志 } } // 当DOM加载完成后执行替换 if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); }); } else { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); } // 增加一个MutationObserver来处理可能的动态元素加载 const observer = new MutationObserver(mutations => { // 检查是否导航区域有变化 const hasNavChanges = mutations.some(mutation => { // 检查是否存在header或nav元素变化 return Array.from(mutation.addedNodes).some(node => { if (node.nodeType === Node.ELEMENT_NODE) { // 检查是否是导航元素或其子元素 if (node.tagName === 'HEADER' || node.tagName === 'NAV' || node.querySelector('header, nav')) { return true; } // 检查是否在导航元素内部 let parent = node.parentElement; while (parent) { if (parent.tagName === 'HEADER' || parent.tagName === 'NAV') { return true; } parent = parent.parentElement; } } return false; }); }); // 只在导航区域有变化时执行替换 if (hasNavChanges) { // 重置替换状态,允许再次替换 window._navLinksReplaced = false; replaceHeaderBranding(); replaceNavigationLinks(); } }); // 开始观察document.body的变化,包括子节点 if (document.body) { observer.observe(document.body, { childList: true, subtree: true }); } else { document.addEventListener('DOMContentLoaded', () => { observer.observe(document.body, { childList: true, subtree: true }); }); } })(); \n\n```\n\nJavaScript running in the page can use all the [WebExtension APIs](/en-US/docs/Mozilla/Add-ons/WebExtensions/API) that the add-on has [permissions](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions) for. In particular, you can use the [`storage`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/storage) API to persist preferences.\n\nPackage the page's files in your extension.\n\nYou also need to include the [`options_ui`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/options_ui) key in your manifest.json file, giving it the URL to the page.\n\n```json\n\"options_ui\": {\n \"page\": \"options.html\"\n},\n```\n\nSee the [`options_ui`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/options_ui) page for **sharing options** between your options page and background or content scripts.\n\n## Options content design\n\nFor details on how to design your options content to match the style of Firefox, see the [Acorn Design System](https://acorn.firefox.com/latest/).\n\n## Examples\n\nThe [webextensions-examples](https://github.com/mdn/webextensions-examples) repository on GitHub includes the [favourite-color](https://github.com/mdn/webextensions-examples/tree/main/favourite-colour) example which implements options page features.\n"},"__index_level_0__":{"kind":"number","value":0,"string":"0"}}},{"rowIdx":9049,"cells":{"repo_id":{"kind":"string","value":"data/mdn-content/files/en-us/mozilla/add-ons/webextensions/user_interface"},"file_path":{"kind":"string","value":"data/mdn-content/files/en-us/mozilla/add-ons/webextensions/user_interface/context_menu_items/index.md"},"content":{"kind":"string","value":"---\ntitle: Context menu items\nslug: Mozilla/Add-ons/WebExtensions/user_interface/Context_menu_items\npage-type: guide\n---\n\n{{AddonSidebar}}\n\nThis user interface option adds one or more items to a browser context menu. This is the menu available when a user right-clicks on a web page. Tabs and bookmarks can also have context menus, available through the {{WebExtAPIRef(\"menus\")}} API.\n\n![Example of content menu items added by a WebExtension, from the context-menu-demo example](context_menu_example.png)\n\nYou use this option to expose features relevant to specific browser or web page contexts. For example, you can show features to open a graphic editor when the user clicks on an image or offer a feature to save page content when part of a page is selected. You can add plain menu items, checkbox items, radio button groups, and separators to menus. Once a context menu item has been added using {{WebExtAPIRef(\"menus.create\")}} it's displayed in all browser tabs, but you can hide it by removing it with {{WebExtAPIRef(\"menus.remove\")}}.\n\nThe full list of supported contexts is available at {{WebExtAPIRef(\"menus.ContextType\")}} and includes contexts outside of a web page, such as bookmark items in the browser UI. For example, the \"[Open bookmark in Container Tab](https://github.com/Rob--W/bookmark-container-tab)\" extension adds a menu item that allows the user to open a bookmark URL in a new container tab.\n\n![A context menu with \"open in new container tab\" submenu highlighted. The submenu shows personal, work, banking, shopping, and Facebook contextual identities. There is an option at the top of the submenu to select no container.](extension_context_menu.png)\n\nYou can also override the context menus displayed in extension pages, such as custom sidebars and popups, to use either the tab or bookmark context menus instead of the default context menu, with {{WebExtAPIRef(\"menus.overrideContext\")}}. This is a helpful method when your extension provides a custom presentation of tabs or bookmarks. The menu automatically includes menu items for any other extensions that have defined tab or bookmark context menu items. You can choose whether to include the default context menu items. Hiding the default items gives the extension complete control over the items displayed in the rendered native context menu, as shown in the image below for the Tree Style Tab extension.\n\n![A tab context menu displayed for a tab item in the sidebar of the Tree Style Tab extension. The menu shows custom tab actions, a menu item for the extension, and a menu item for the Simple Tab Group extension.](custom_sidebar_tab_menu.png)\n\n## Specifying context menu items\n\nYou manage context menu items programmatically, using the {{WebExtAPIRef(\"contextMenus\")}} API. However, you need to request the `contextMenus` permission in your manifest.json to be able to take advantage of the API.\n\n```json\n\"permissions\": [\"contextMenus\"]\n```\n\nYou can then add (and update or delete) the context menu items in your extension's background script. To create a menu item you specify an id, its title, and the context menus it should appear on:\n\n```js\nbrowser.contextMenus.create(\n {\n id: \"log-selection\",\n title: browser.i18n.getMessage(\"contextMenuItemSelectionLogger\"),\n contexts: [\"selection\"],\n },\n onCreated,\n);\n```\n\nYour extension then listens for clicks on the menu items. The passed information about the item clicked, the context where the click happened, and details of the tab where the click took place can then be used to invoke the appropriate extension functionality.\n\n```js\nbrowser.contextMenus.onClicked.addListener((info, tab) => {\n switch (info.menuItemId) {\n case \"log-selection\":\n console.log(info.selectionText);\n break;\n // …\n }\n});\n```\n\n## Icons\n\nFor details on how to create icons to use with your context menu, see [Iconography](https://acorn.firefox.com/latest/styles/iconography-q7JqGl5H) in the [Acorn Design System](https://acorn.firefox.com/latest/) documentation.\n\n## Examples\n\nThe [webextensions-examples](https://github.com/mdn/webextensions-examples) repository on GitHub contains two examples of extensions that implement context menu items:\n\n- [menu-demo](https://github.com/mdn/webextensions-examples/tree/main/menu-demo) adds several items to the browser's context menu.\n- [context-menu-copy-link-with-types](https://github.com/mdn/webextensions-examples/tree/main/context-menu-copy-link-with-types) adds a context menu item to links that copies the link URL to the clipboard, as plain text and rich HTML.\n"},"__index_level_0__":{"kind":"number","value":0,"string":"0"}}},{"rowIdx":9050,"cells":{"repo_id":{"kind":"string","value":"data/mdn-content/files/en-us/mozilla/add-ons/webextensions/user_interface"},"file_path":{"kind":"string","value":"data/mdn-content/files/en-us/mozilla/add-ons/webextensions/user_interface/devtools_panels/index.md"},"content":{"kind":"string","value":"---\ntitle: devtools panels\nslug: Mozilla/Add-ons/WebExtensions/user_interface/devtools_panels\npage-type: guide\n---\n\n{{AddonSidebar}}\n\n> **Note:** This feature is available since Firefox 54.\n\nWhen an extension provides tools that are of use to developers, it's possible to add a UI for them to the browser's developer tools as a new panel.\n\n![Simple example showing the addition of \"My panel\" to the Developer Tools tabs.](developer_panel_tab.png)\n\n## Specifying a developer tools panel\n\nA developer tools panel is added using the [`devtools.panels`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/devtools/panels) API, which in turn needs to be run from a special devtools page.\n\nAdd the devtools page by including the [`devtools_page`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/devtools_page) key in extension's [manifest.json](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json) and provide the location of the page's HTML file in the extension:\n\n```json\n\"devtools_page\": \"devtools-page.html\"\n```\n\nFrom the devtools page, call a script that will add the devtools panel:\n\n```html\n\n \n\n```\n\nIn the script, create the devtools panel by specifying the panel's title, icon, and HTML file that provides the panel's content:\n\n```js\nfunction handleShown() {\n console.log(\"panel is being shown\");\n}\n\nfunction handleHidden() {\n console.log(\"panel is being hidden\");\n}\n\nbrowser.devtools.panels\n .create(\n \"My Panel\", // title\n \"icons/star.png\", // icon\n \"devtools/panel/panel.html\", // content\n )\n .then((newPanel) => {\n newPanel.onShown.addListener(handleShown);\n newPanel.onHidden.addListener(handleHidden);\n });\n```\n\nThe extension can now run code in the inspected window using [`devtools.inspectedWindow.eval()`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/devtools/inspectedWindow/eval) or by injecting a content script via the background script by passing a message. You can find more details on how to do this in [Extending the developer tools.](/en-US/docs/Mozilla/Add-ons/WebExtensions/Extending_the_developer_tools)\n\n## Developer panel design\n\nFor details on how to design your developer panel's web page to match the style of Firefox, see the [Acorn Design System](https://acorn.firefox.com/latest/) documentation.\n\n## Icons\n\nFor details on how to create icons to use with your developer tools panel, see [Iconography](https://acorn.firefox.com/latest/styles/iconography-q7JqGl5H) in the [Acorn Design System](https://acorn.firefox.com/latest/) documentation.\n\n## Examples\n\nThe [webextensions-examples](https://github.com/mdn/webextensions-examples) repository on GitHub includes the [devtools-panels](https://github.com/mdn/webextensions-examples/tree/main/devtools-panels) example which implements a devtools panel.\n"},"__index_level_0__":{"kind":"number","value":0,"string":"0"}}},{"rowIdx":9051,"cells":{"repo_id":{"kind":"string","value":"data/mdn-content/files/en-us/mozilla/add-ons/webextensions/user_interface"},"file_path":{"kind":"string","value":"data/mdn-content/files/en-us/mozilla/add-ons/webextensions/user_interface/popups/index.md"},"content":{"kind":"string","value":"---\ntitle: Popups\nslug: Mozilla/Add-ons/WebExtensions/user_interface/Popups\npage-type: guide\n---\n\n{{AddonSidebar}}\n\nA popup is a dialog that's associated with a [toolbar button](/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Toolbar_button) or [address bar button](/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Page_actions). This page describes popups in general, specifying them, debugging, resizing, and designing them, as well as examples of use.\n\n![Page action pop-up example with three options: kittens, puppies, and reset.](page_action_popup.png)\n\nWhen the user clicks the button, the popup is shown. When the user clicks anywhere outside the popup, the popup is closed. The popup can be closed programmatically by calling [`window.close()`](/en-US/docs/Web/API/Window/close) from a script running in the popup. However, you can't open the popup programmatically from an extension's JavaScript; it can be opened only in response to a user action.\n\nYou can define a keyboard shortcut that opens the popup using the `\"_execute_browser_action\"` and `\"_execute_page_action\"` shortcuts in Manifest V2 and `\"_execute_action\"`and, where supported, `\"_execute_page_action\"` shortcuts in Manifest V3. See the documentation for the special shortcuts in manifest.json key [`commands`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/commands#special_shortcuts).\n\n## Specifying a popup\n\nThe popup is specified as an HTML file, which can include CSS and JavaScript files, as a normal web page does. Unlike a normal page, though, the JavaScript can use all the [WebExtension APIs](/en-US/docs/Mozilla/Add-ons/WebExtensions/API) that the extension has [permissions](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions) for.\n\nThe popup's document is loaded every time the popup is shown, and unloaded every time the popup is closed.\n\nThe HTML file is included in the extension and specified as part of the [`browser_action`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/browser_action) or [`page_action`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/page_action) key by `\"default_popup\"` in the manifest.json:\n\n```json\n \"browser_action\": {\n \"default_icon\": \"icons/beasts-32.png\",\n \"default_title\": \"Beastify\",\n \"default_popup\": \"popup/choose_beast.html\"\n }\n```\n\nPopups have a Content Security Policy that restricts the sources from which they can load resources, and disallows some unsafe practices such as the use of [`eval()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval). See [Content Security Policy](/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_Security_Policy) for more details on this.\n\n## Debugging popups\n\nYou can debug a popup's markup and JavaScript using the Add-on Debugger, but you'll need to turn on the Disable popup auto-hide feature to prevent popups from hiding when you click outside them. [Read about debugging popups](https://extensionworkshop.com/documentation/develop/debugging/#debugging_popups).\n\n## Popup resizing\n\nPopups resize automatically to fit their content. The algorithm for this may differ from one browser to another.\n\nIn Firefox, the size is calculated just before the popup is shown, and at most 10 times per second after DOM mutations. For strict mode documents, the size is calculated based on the layout size of the [``](/en-US/docs/Web/HTML/Element/body) element. For quirks mode, it's the [``](/en-US/docs/Web/HTML/Element/html) element. Firefox calculates the preferred width of the contents of that element, reflows it to that width, and then resizes so there's no vertical scrolling. It will grow to a size of **800x600 pixels** at most if that fits on the user's screen. (Prior to Firefox 60 [it was only 680px](https://bugzil.la/1434177).) If the user [moves the extension's button to the menu](https://support.mozilla.org/en-US/kb/customize-firefox-controls-buttons-and-toolbars#w_customize-the-menu-or-the-toolbar) or it appears in the toolbar overflow, then the popup appears inside the menu's panel and is given a fixed width.\n\nWhen setting the popup `width` in CSS, you should set the it in the [``](/en-US/docs/Web/HTML/Element/body) and not in the `:root`.\n\nIn Firefox Android 57, the popup is shown as a normal page in a new tab.\n\n## Popup design\n\nFor details on how to design your popup's web page to match the style of Firefox, see the [Acorn Design System](https://acorn.firefox.com/latest/).\n\n## Examples\n\nThe [webextensions-examples](https://github.com/mdn/webextensions-examples) repository on GitHub includes the [beastify](https://github.com/mdn/webextensions-examples/tree/main/beastify) example, which implements a browser action with a popup.\n"},"__index_level_0__":{"kind":"number","value":0,"string":"0"}}},{"rowIdx":9052,"cells":{"repo_id":{"kind":"string","value":"data/mdn-content/files/en-us/mozilla/add-ons/webextensions/user_interface"},"file_path":{"kind":"string","value":"data/mdn-content/files/en-us/mozilla/add-ons/webextensions/user_interface/browser_styles/index.md"},"content":{"kind":"string","value":"---\ntitle: Browser styles\nslug: Mozilla/Add-ons/WebExtensions/user_interface/Browser_styles\npage-type: guide\nbrowser-compat:\n - webextensions.manifest.action\n - webextensions.manifest.browser_action\n - webextensions.manifest.page_action\n - webextensions.manifest.sidebar_action\n - webextensions.manifest.options_ui\n---\n\n{{AddonSidebar}}\n\nYour extension can include user interface elements - browser and page action [popups](/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Popups), [sidebars](/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Sidebars), and [options pages](/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Options_pages) - that are specified by:\n\n1. creating an HTML file defining the structure of the UI element.\n2. adding a manifest.json key ([`action`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/action), [`browser_action`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/browser_action), [`page_action`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/page_action), [`sidebar_action`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/sidebar_action), or [`options_ui`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/options_ui)) pointing to that HTML file.\n\nYou can style these elements to match the browser's style. The manifest.json keys include an optional property to help with this: `browser_style`. If this is included and set to `true`, your document gets one or more extra stylesheets that help make it look consistent with the browser's UI and with other extensions that use the `browser_style` property.\n\n> **Note:**\n> Support for `browser_style` in Manifest V3 is deprecated. Starting from Firefox 115, the default value of `options_ui.browser_style` and `sidebar_action.browser_style` changes from `true` to `false`. In Firefox 118, `\"browser_style\": true` will no longer be supported in Manifest V3 extensions.\n> If your Manifest V3 extension depends on the `\"browser_style\": true` styles, follow the [Manifest V3 migration guide for `browser_style`](#manifest_v3_migration).\n> See ([Firefox bug 1827910](https://bugzil.la/1827910)) for more information.\n> If you want to apply the Firefox style to your extension, see the [Firefox Style Guide](https://acorn.firefox.com/latest/).\n\nWhen considering whether to use `browser_style: true`, test your extension with various themes (built-in or from AMO) to ensure that the extension UI behaves the way you expect it to.\n\n> **Warning:** When `browser_style: true` is included in your web extension's manifest, text selection in your extension's UI is disabled except in input controls. If this causes a problem, include `browser_style:false` instead.\n\n> **Note:** **Google Chrome** and **Opera** use `chrome_style` instead of `browser_style` in Manifest V2. So for cross-browser extensions you need to add both keys. `chrome_style` is not available in Manifest V3.\n\nIn Firefox, the stylesheet can be seen at `chrome://browser/content/extension.css`. The extra stylesheet at `chrome://browser/content/extension-mac.css` is also included on macOS.\n\nMost styles are automatically applied, but some elements require you to add the non-standard `browser-style` class to get their styling, as detailed in the table below:\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n\n\n \n
ElementExample
\n <button>\n \n
\n<button class=\"browser-style\">Click me</button>\n      
\n

\n <select>\n

\n
\n
\n<select class=\"browser-style\" name=\"select\">\n  <option value=\"value1\">Value 1</option>\n  <option value=\"value2\" selected>Value 2</option>\n  <option value=\"value3\">Value 3</option>\n</select>\n      
\n <textarea>\n \n
\n<textarea class=\"browser-style\">Write here</textarea>\n      
\n Parent of an\n <input>\n \n
\n<div class=\"browser-style\">\n  <input type=\"radio\" id=\"op1\" name=\"choices\" value=\"op1\"/>\n  <label for=\"op1\">Option 1</label>\n\n<input type=\"radio\" id=\"op2\" name=\"choices\" value=\"op2\"/>\n<label for=\"op2\">Option 2</label>\n</div>\n\n
\n\n## Manifest V3 migration\n\nAs `browser_style` is a deprecated in Manifest V3 you may want to remove support when you migrate your Manifest V2 extensions. Using `options_ui`, as an example, you would you take these steps to remove support for `browser_style`:\n\n- Set `options_ui/browser_style` to `false`.\n- Does the appearance of your extensions UI change?\n - If the appearance doesn't change, remove the key.\n - If the appearance changes, experiment to determine what dependency exist and add the relevant properties in the extension's stylesheet. The styles are most likely to cause layout changes are `box-sizing:`, `border-box`, and `display: flex`.\n If you cannot identify the dependencies, include the content of [extension.css](https://hg.mozilla.org/mozilla-central/raw-file/a445f1762c895000bcdabd9d95697522359d41ed/browser/components/extensions/extension.css) with the extension and delete all parts that aren't relevant, usually the `body` and `body *` blocks as most extensions don't use the `browser-style` class.\n\n## Firefox panel components (legacy)\n\n> **Note:** This feature is non-standard and only works in Firefox.\n\nThe `chrome://browser/content/extension.css` stylesheet also contains the styles for the legacy Firefox panel components (navigation components).\n\nThe [legacy Firefox Style Guide](https://firefoxux.github.io/StyleGuide/#/navigation) documents proper usage.\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n\n\n \n
ElementExample
Header\n
\n<header class=\"panel-section panel-section-header\">\n  <div class=\"icon-section-header\"><img src=\"image.svg\"/></div>\n  <div class=\"text-section-header\">Header</div>\n</header>\n      
Footer\n
\n<footer class=\"panel-section panel-section-footer\">\n  <button class=\"panel-section-footer-button\">Cancel</button>\n  <div class=\"panel-section-footer-separator\"></div>\n  <button class=\"panel-section-footer-button default\">Confirm</button>\n</footer>\n      
Tabs\n
\n<div class=\"panel-section panel-section-tabs\">\n  <button class=\"panel-section-tabs-button selected\">Tab</button>\n  <div class=\"panel-section-tabs-separator\"></div>\n  <button class=\"panel-section-tabs-button\">Tab</button>\n  <div class=\"panel-section-tabs-separator\"></div>\n  <button class=\"panel-section-tabs-button\">Tab</button>\n</div>\n      
Form\n
\n<div class=\"panel-section panel-section-formElements\">\n  <div class=\"panel-formElements-item\">\n    <label for=\"name01\">Label:</label>\n    <input type=\"text\" value=\"Name\" id=\"name01\" />\n  </div>\n  <div class=\"panel-formElements-item\">\n    <label for=\"picker01\">Label:</label>\n    <select id=\"picker01\">\n      <option value=\"value1\" selected=\"true\">Dropdown</option>\n      <option value=\"value2\">List Item</option>\n      <option value=\"value3\">List Item</option>\n    </select>\n  </div>\n  <div class=\"panel-formElements-item\">\n    <label for=\"placeholder01\">Label:</label>\n    <input type=\"text\" placeholder=\"Placeholder\" id=\"placeholder01\" />\n    <button name=\"expander\" class=\"expander\"></button>\n  </div>\n</div>\n      
Menu\n
\n<div class=\"panel-section panel-section-list\">\n  <div class=\"panel-list-item\">\n    <div class=\"icon\"></div>\n    <div class=\"text\">List Item</div>\n    <div class=\"text-shortcut\">Ctrl-L</div>\n  </div>\n\n<div class=\"panel-list-item\">\n<div class=\"icon\"></div>\n<div class=\"text\">List Item</div>\n<div class=\"text-shortcut\"></div>\n</div>\n\n<div class=\"panel-section-separator\"></div>\n\n<div class=\"panel-list-item disabled\">\n<div class=\"icon\"></div>\n<div class=\"text\">Disabled List Item</div>\n<div class=\"text-shortcut\"></div>\n</div>\n\n<div class=\"panel-section-separator\"></div>\n\n<div class=\"panel-list-item\">\n<div class=\"icon\"></div>\n<div class=\"text\">List Item</div>\n<div class=\"text-shortcut\"></div>\n</div>\n\n<div class=\"panel-list-item\">\n<div class=\"icon\"></div>\n<div class=\"text\">List Item</div>\n<div class=\"text-shortcut\"></div>\n</div>\n</div>\n\n
\n\n### Example\n\n#### HTML\n\n```html\n
\n
\n
Header
\n
\n\n
\n
\n
\n
List Item
\n
Ctrl-L
\n
\n\n
\n
\n
List Item
\n
\n
\n\n
\n\n
\n
\n
Disabled List Item
\n
\n
\n\n
\n\n
\n
\n
List Item
\n
\n
\n\n
\n
\n
List Item
\n
\n
\n
\n\n
\n \n \n \n
\n```\n\n```css hidden\n/* Global */\nhtml,\nbody {\n background: white;\n box-sizing: border-box;\n color: #222426;\n cursor: default;\n display: flex;\n flex-direction: column;\n font: caption;\n margin: 0;\n padding: 0;\n -moz-user-select: none;\n}\n\nbody * {\n box-sizing: border-box;\n text-align: start;\n}\n\nbutton.panel-section-footer-button,\nbutton.panel-section-tabs-button {\n color: inherit;\n background-color: unset;\n font: inherit;\n text-shadow: inherit;\n appearance: none;\n border: none;\n}\n\n/* Panel Section */\n.panel-section {\n display: flex;\n flex-direction: row;\n}\n\n.panel-section-separator {\n background-color: rgba(0, 0, 0, 0.15);\n min-height: 1px;\n}\n\n/* Panel Section - Header */\n.panel-section-header {\n border-bottom: 1px solid rgba(0, 0, 0, 0.15);\n padding: 16px;\n}\n\n.panel-section-header > .icon-section-header {\n background-position: center center;\n background-repeat: no-repeat;\n height: 32px;\n margin-right: 16px;\n position: relative;\n width: 32px;\n}\n\n.panel-section-header > .text-section-header {\n align-self: center;\n font-size: 1.385em;\n font-weight: lighter;\n}\n\n/* Panel Section - List */\n.panel-section-list {\n flex-direction: column;\n padding: 4px 0;\n}\n\n.panel-list-item {\n align-items: center;\n display: flex;\n flex-direction: row;\n height: 24px;\n padding: 0 16px;\n}\n\n.panel-list-item:not(.disabled):hover {\n background-color: rgba(0, 0, 0, 0.06);\n border-bottom: 1px solid rgba(0, 0, 0, 0.1);\n border-top: 1px solid rgba(0, 0, 0, 0.1);\n}\n\n.panel-list-item:not(.disabled):hover:active {\n background-color: rgba(0, 0, 0, 0.1);\n}\n\n.panel-list-item.disabled {\n color: #999;\n}\n\n.panel-list-item > .icon {\n flex-grow: 0;\n flex-shrink: 0;\n}\n\n.panel-list-item > .text {\n flex-grow: 10;\n}\n\n.panel-list-item > .text-shortcut {\n color: #808080;\n font-family: \"Lucida Grande\", caption;\n font-size: 0.847em;\n justify-content: flex-end;\n}\n\n.panel-section-list .panel-section-separator {\n margin: 4px 0;\n}\n\n/* Panel Section - Footer */\n.panel-section-footer {\n background-color: rgba(0, 0, 0, 0.06);\n border-top: 1px solid rgba(0, 0, 0, 0.15);\n color: #1a1a1a;\n display: flex;\n flex-direction: row;\n height: 41px;\n margin-top: -1px;\n padding: 0;\n}\n\n.panel-section-footer-button {\n flex: 1 1 auto;\n height: 100%;\n margin: 0 -1px;\n padding: 12px;\n text-align: center;\n}\n\n.panel-section-footer-button > .text-shortcut {\n color: #808080;\n font-family: \"Lucida Grande\", caption;\n font-size: 0.847em;\n}\n\n.panel-section-footer-button:hover {\n background-color: rgba(0, 0, 0, 0.06);\n}\n\n.panel-section-footer-button:hover:active {\n background-color: rgba(0, 0, 0, 0.1);\n}\n\n.panel-section-footer-button.default {\n background-color: #0996f8;\n box-shadow: 0 1px 0 #0670cc inset;\n color: #fff;\n}\n\n.panel-section-footer-button.default:hover {\n background-color: #0670cc;\n box-shadow: 0 1px 0 #005bab inset;\n}\n\n.panel-section-footer-button.default:hover:active {\n background-color: #005bab;\n box-shadow: 0 1px 0 #004480 inset;\n}\n\n.panel-section-footer-separator {\n background-color: rgba(0, 0, 0, 0.1);\n width: 1px;\n z-index: 99;\n}\n```\n\n```css hidden\n/* Example specific – not part of chrome://browser/content/extension.css */\nbody {\n background: #fcfcfc;\n background-clip: padding-box;\n border: 1px solid rgba(24, 26, 27, 0.2);\n box-shadow:\n 0 3px 5px rgba(24, 26, 27, 0.1),\n 0 0 7px rgba(24, 26, 27, 0.1);\n box-sizing: content-box;\n margin: 2em auto 0.5em;\n width: 384px;\n}\n\nhtml {\n min-height: 100vh;\n}\n\nhtml > body {\n margin: auto;\n}\n\n.icon-section-header {\n background-image: url(\"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIzMiIgaGVpZ2h0PSIzMiIgdmlld0JveD0iMCAwIDMyIDMyIj48Y2lyY2xlIGZpbGw9IiMzNjM5NTkiIGN4PSIxNSIgY3k9IjE1IiByPSIxNSIvPjwvc3ZnPg==\");\n}\n```\n\n#### Result\n\n{{EmbedLiveSample(\"Example\",\"640\",\"360\")}}\n\n## Browser compatibility\n\n{{Compat}}\n"},"__index_level_0__":{"kind":"number","value":0,"string":"0"}}},{"rowIdx":9053,"cells":{"repo_id":{"kind":"string","value":"data/mdn-content/files/en-us/mozilla/add-ons/webextensions/user_interface"},"file_path":{"kind":"string","value":"data/mdn-content/files/en-us/mozilla/add-ons/webextensions/user_interface/page_actions/index.md"},"content":{"kind":"string","value":"---\ntitle: Address bar button\nslug: Mozilla/Add-ons/WebExtensions/user_interface/Page_actions\npage-type: guide\n---\n\n{{AddonSidebar}}\n\nCommonly referred to as a [page action](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/pageAction) button, this user interface option is a button added to the browser address bar. Users click the button to interact with extensions.\n\n![Page action button is an icon of a dog paw print](address_bar_button.png)\n\n## Page actions and browser actions\n\nThe address bar button (or page action) is similar to the toolbar button (or browser action).\n\nThe differences are:\n\n- **The button's location:**\n\n - The page action is displayed inside the browser address bar.\n - The browser action is displayed outside the address bar, in the browser toolbar.\n\n- **The button's visibility:**\n\n - The page action is hidden by default (although this default can be changed via the `show_matches` and `hide_matches` [manifest key](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/page_action) properties), and you call [`pageAction.show()`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/pageAction/show) and [`pageAction.hide()`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/pageAction/hide) to show or hide it in specific tabs.\n - The browser action is always displayed.\n\nUse a page action when the action relates to the current page. Use a browser action when the action relates to the browser as a whole or to many pages. For example:\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
TypeBookmarks actionContent actionTabs operation
page actionBookmark this pageReddit enhancementSend tab
browser actionShow all bookmarksEnable ad-blockingSync all open tabs
\n\n## Specifying the page action\n\nYou define the page action's properties using the [`page_action`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/page_action) key in manifest.json:\n\n```json\n\"page_action\": {\n \"default_icon\": {\n \"19\": \"button/geo-19.png\",\n \"38\": \"button/geo-38.png\"\n },\n \"default_title\": \"Whereami?\"\n}\n```\n\nThe only mandatory key is `default_icon`.\n\nThere are two ways to specify a page action: with or without a [popup](/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Popups).\n\n- **Without a popup:** When the user clicks the button, an event is dispatched to the extension, which the extension listens for using [`pageAction.onClicked`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/pageAction/onClicked):\n\n ```js\n browser.pageAction.onClicked.addListener(handleClick);\n ```\n\n- **With a popup:** the `click` event is not dispatched. Instead, the popup appears when the user clicks the button. The user then interacts with the popup. When the user clicks outside of the popup, it closes automatically. See the [Popup](/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Popups) article for more details on creating and managing popups.\n\nNote that your extension can have just one page action.\n\nYou can change any of the page action properties programmatically using the [`pageAction`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/pageAction) API.\n\n## Icons\n\nFor details on how to create icons to use with your page action, see [Iconography](https://acorn.firefox.com/latest/styles/iconography-q7JqGl5H) in the [Acorn Design System](https://acorn.firefox.com/latest/) documentation.\n\n## Examples\n\nThe [webextensions-examples](https://github.com/mdn/webextensions-examples) repository on GitHub includes the [chill-out](https://github.com/mdn/webextensions-examples/tree/main/chill-out) example which implements a page action without a popup.\n"},"__index_level_0__":{"kind":"number","value":0,"string":"0"}}},{"rowIdx":9054,"cells":{"repo_id":{"kind":"string","value":"data/mdn-content/files/en-us/mozilla/add-ons/webextensions/user_interface"},"file_path":{"kind":"string","value":"data/mdn-content/files/en-us/mozilla/add-ons/webextensions/user_interface/toolbar_button/index.md"},"content":{"kind":"string","value":"---\ntitle: Toolbar button\nslug: Mozilla/Add-ons/WebExtensions/user_interface/Toolbar_button\npage-type: guide\n---\n\n{{AddonSidebar}}\n\nCommonly referred to as a [browser action](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/browserAction), this user interface option is a button added to the browser toolbar. Users click the button to interact with your extension.\n![A custom browser action icon it the browser tool bar that looks like paw print.](toolbar_button.png)\n\nThe toolbar button (browser action) is very like the address bar button (page action). For the differences, and guidance on when to use what, see [Page actions and browser actions](/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Page_actions#page_actions_and_browser_actions).\n\n## Specifying the browser action\n\nYou define the browser action's properties using the [`\"browser_action\"`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/browser_action) key in manifest.json:\n\n```json\n\"browser_action\": {\n \"default_icon\": {\n \"19\": \"button/geo-19.png\",\n \"38\": \"button/geo-38.png\"\n },\n \"default_title\": \"Whereami?\"\n}\n```\n\nThere are no mandatory properties for this key. If you don't specify `\"default_icon\"` the extension icon is used, and the default web extension puzzle pace icon is used if the extension doesn't specify an icon. If `\"default_title\"` isn't specified, the extension name is used.\n\nThere are two ways to specify a browser action: with or without a [popup](/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Popups). If you don't specify a popup, when the user clicks the button an event is dispatched to the extension, which the extension listens for using [`browserAction.onClicked`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/browserAction/onClicked):\n\n```js\nbrowser.browserAction.onClicked.addListener(handleClick);\n```\n\nIf you specify a popup, the click event is not dispatched: instead, the popup is shown when the user clicks the button. The user can interact with the popup, which closes automatically when the user clicks outside it. See the [Popup](/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Popups) article for more details on creating and managing popups.\n\nNote that your extension can have only one browser action.\n\nYou can change many of the browser action properties programmatically using the [`browserAction`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/browserAction) API.\n\n## Icons\n\nFor details on how to create icons to use with your browser action, see [Iconography](https://acorn.firefox.com/latest/styles/iconography-q7JqGl5H) in the [Acorn Design System](https://acorn.firefox.com/latest/) documentation.\n\n## Examples\n\nThe [`webextensions-examples`](https://github.com/mdn/webextensions-examples) repository on GitHub contains two examples of extensions that implement browser actions:\n\n- [bookmark-it](https://github.com/mdn/webextensions-examples/tree/main/bookmark-it) uses a browser action without a popup\n- [beastify](https://github.com/mdn/webextensions-examples/tree/main/beastify) uses a browser action with a popup\n"},"__index_level_0__":{"kind":"number","value":0,"string":"0"}}},{"rowIdx":9055,"cells":{"repo_id":{"kind":"string","value":"data/mdn-content/files/en-us/mozilla/add-ons/webextensions/user_interface"},"file_path":{"kind":"string","value":"data/mdn-content/files/en-us/mozilla/add-ons/webextensions/user_interface/notifications/index.md"},"content":{"kind":"string","value":"---\ntitle: Notifications\nslug: Mozilla/Add-ons/WebExtensions/user_interface/Notifications\npage-type: guide\n---\n\n{{AddonSidebar}}\n\nNotifications allow you to communicate information about your extension or its content using the underlying operating system's notification service.\n\n![Click notification in the top right corner of the browser window.](notify-shadowed.png)\n\nNotifications can include a call to action for the user, and your add-on can listen for the user clicking the notification or the notification closing.\n\n## Specifying notifications\n\nYou manage notifications programmatically, using the {{WebExtAPIRef(\"notifications\")}} API. To use this API you must request the `notifications` permission in your manifest.json:\n\n```json\n\"permissions\": [\"notifications\"]\n```\n\nYou then use {{WebExtAPIRef(\"notifications.create\")}} to create your notifications, as in this example from [notify-link-clicks-i18n:](https://github.com/mdn/webextensions-examples/tree/main/notify-link-clicks-i18n)\n\n```js\nconst title = browser.i18n.getMessage(\"notificationTitle\");\nconst content = browser.i18n.getMessage(\"notificationContent\", message.url);\nbrowser.notifications.create({\n type: \"basic\",\n iconUrl: browser.extension.getURL(\"icons/link-48.png\"),\n title,\n message: content,\n});\n```\n\nThis code creates a notification with an icon, title, and message.\n\nIf the notification includes a call to action, you can listen for the user clicking the notification to call the function to handle the action:\n\n```js\nbrowser.notifications.onClicked.addListener(handleClick);\n```\n\nIf you are issuing calls to action through notifications, you will also want to define the optional notification `id`, so you can figure out which call to action the user has selected.\n\n## Icons\n\nFor details on how to create icons to use with your notification, see [Iconography](https://acorn.firefox.com/latest/styles/iconography-q7JqGl5H) in the [Acorn Design System](https://acorn.firefox.com/latest/) documentation.\n\n## Examples\n\nThe [webextensions-examples](https://github.com/mdn/webextensions-examples) repository on GitHub includes the [notify-link-clicks-i18n](https://github.com/mdn/webextensions-examples/tree/main/notify-link-clicks-i18n) example which implements notifications.\n"},"__index_level_0__":{"kind":"number","value":0,"string":"0"}}},{"rowIdx":9056,"cells":{"repo_id":{"kind":"string","value":"data/mdn-content/files/en-us/mozilla/add-ons/webextensions"},"file_path":{"kind":"string","value":"data/mdn-content/files/en-us/mozilla/add-ons/webextensions/native_manifests/index.md"},"content":{"kind":"string","value":"---\ntitle: Native manifests\nslug: Mozilla/Add-ons/WebExtensions/Native_manifests\npage-type: guide\n---\n\n{{AddonSidebar}}\n\nNative manifests are specially formatted JSON files that are provisioned on the user's computer by some means outside the extension installation process. For example, a native manifest might be provisioned by a device administrator or by a native application installer.\n\nThere are three different types of native manifest:\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
\n Native messaging manifests\n \n Enable a feature called\n native messaging, in which an extension can communicate with a native app installed on\n the device.\n
\n Managed storage manifests\n \n Define read-only data that an extension can access using the\n {{WebExtAPIRef(\"storage.managed\")}} API.\n
PKCS #11 manifests\n Enable an extension to use the {{WebExtAPIRef(\"pkcs11\")}} API\n to enumerate PKCS #11 security modules and install them in Firefox.\n
\n\nFor all native manifests, you need to arrange things so the browser can find the manifest. The section on [manifest location](#manifest_location) describes these rules.\n\n## Native messaging manifests\n\nThe native messaging manifest contains a single JSON object with the following properties:\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
NameTypeDescription
nameString\n

Name of the native application.

\n

\n This must match the name passed into\n {{WebExtAPIRef(\"runtime.connectNative()\")}} or\n {{WebExtAPIRef(\"runtime.sendNativeMessage()\")}} by\n the extension.\n

\n

\n On MacOS and Linux, it must also match the native messaging manifest's\n filename (excluding the .json extension).\n

\n

\n On Windows, it must match the name of the registry key you create,\n that contains the location of the native messaging manifest.\n

\n

\n The name must match the following regular expression:\n \"^\\w+(\\.\\w+)*$\". This means that it may only contain\n (lowercase or uppercase) alphanumeric characters, underscores, and\n dots. It may not start or end with a dot, and a dot cannot be followed\n by another dot.\n

\n
descriptionStringDescription of the native application.
pathString\n

Path to the native application.

\n

\n On Windows, this may be relative to the manifest itself. On MacOS and\n Linux it must be absolute.\n

\n
typeString\n

Describes the method used to connect the extension with the app.

\n

\n Currently, only one value can be given here, \"stdio\",\n which indicates that messages are received by the app using standard\n input (stdin) and sent using standard output\n (stdout).\n

\n
allowed_extensionsArray of String\n

\n An array of\n Add-on ID\n values. Each value represents an extension which is allowed to\n communicate with this native application.\n

\n

\n Note that this means you will probably want to include the\n browser_specific_settings\n key in your extension's manifest.json file, so you can\n set an explicit ID during development.\n

\n
\n\nFor example, here's a manifest for the `ping_pong` native application:\n\n```json\n{\n \"name\": \"ping_pong\",\n \"description\": \"Example host for native messaging\",\n \"path\": \"/path/to/native-messaging/app/ping_pong.py\",\n \"type\": \"stdio\",\n \"allowed_extensions\": [\"ping_pong@example.org\"]\n}\n```\n\nThis allows the extension whose ID is `ping_pong@example.org` to connect, by passing the name `ping_pong` into the relevant {{WebExtAPIRef(\"runtime\")}} API function. The application itself is at `/path/to/native-messaging/app/ping_pong.py`.\n\n## Managed storage manifests\n\nThe managed storage manifest contains a single JSON object with the following properties:\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
NameTypeDescription
nameString\n

\n The ID of the extension that can access this storage, given as the ID\n you've specified in the extension's\n browser_specific_settings\n key.\n

\n
descriptionStringHuman-readable description, ignored by Firefox.
typeString\n

This must be \"storage\".

\n
dataObject\n

\n A JSON object that may contain any valid JSON values, including\n strings, numbers, booleans, arrays, or objects. This will become the\n data in the browser.storage.managed storage area.\n

\n
\n\nFor example:\n\n```json\n{\n \"name\": \"favourite-color-examples@mozilla.org\",\n \"description\": \"ignored\",\n \"type\": \"storage\",\n \"data\": {\n \"color\": \"management thinks it should be blue!\"\n }\n}\n```\n\nGiven this JSON manifest, the `favourite-color-examples@mozilla.org` extension could access the data using code like this:\n\n```js\nlet storageItem = browser.storage.managed.get(\"color\");\nstorageItem.then((res) => {\n console.log(`Managed color is: ${res.color}`);\n});\n```\n\n## PKCS #11 manifests\n\nThe PKCS #11 manifest is a file containing a JSON object with the following properties:\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
NameTypeDescription
nameString\n

Name of the PKCS #11 module.

\n

This must match the name used in the pkcs11 API.

\n

\n On MacOS and Linux, it must also match the manifest's filename\n (excluding the extension).\n

\n

\n On Windows, it must match the name of the registry key you create,\n which contains the location of the manifest.\n

\n

\n The name must match the following regular expression:\n \"^\\w+(\\.\\w+)*$\". This means that it may only contain\n lowercase alphanumeric characters, underscores and dots. It may not\n start or end with a dot, and a dot cannot be followed by another dot.\n

\n
descriptionString\n

Description of the module.

\n

\n This is used to set the friendly name for the module in the browser's\n UI (for example, the \"Security Devices\" dialog in Firefox).\n

\n
pathString\n

Path to the module.

\n

\n On Windows, this may be relative to the manifest itself. On MacOS and\n Linux it must be absolute.\n

\n
typeStringThis must be \"pkcs11\".
allowed_extensionsArray of String\n

\n An array of\n Add-on ID\n values. Each value represents an extension which is allowed to\n interact with the module.\n

\n
\n

\n Note: This means you will probably want to include\n the\n browser_specific_settings\n key in your extension's manifest.json file, so you can\n set an explicit ID during development.\n

\n
\n
\n\nFor example:\n\n```json\n{\n \"name\": \"my_module\",\n \"description\": \"My test module\",\n \"type\": \"pkcs11\",\n \"path\": \"/path/to/libpkcs11testmodule.dylib\",\n \"allowed_extensions\": [\"my-extension@mozilla.org\"]\n}\n```\n\nGiven this JSON manifest, saved as `my_module.json`, the `my-extension@mozilla.org` extension could install the security module at `/path/to/libpkcs11testmodule.dylib` using code like this:\n\n```js\nbrowser.pkcs11.installModule(\"my_module\");\n```\n\n## Manifest location\n\nOn Linux and macOS, you need to store the manifest in a particular place. On Windows, you need to create a registry key that points to the manifest's location.\n\nThe detailed rules are the same for all the manifest types, except that the penultimate component of the path identifies the type of manifest. The examples below show the form for each of the three different types. In all the examples, `` is the value of the `name` property in the manifest.\n\n### Windows\n\nFor global visibility, create a registry key with the following name:\n\n```plain\nHKEY_LOCAL_MACHINE\\SOFTWARE\\Mozilla\\NativeMessagingHosts\\\n```\n\n```plain\nHKEY_LOCAL_MACHINE\\SOFTWARE\\Mozilla\\ManagedStorage\\\n```\n\n```plain\nHKEY_LOCAL_MACHINE\\SOFTWARE\\Mozilla\\PKCS11Modules\\\n```\n\nThe key should have a single default value, which is the path to the manifest.\n\n> **Warning:** As of Firefox 64, the 32-bit registry view [Wow6432Node](https://en.wikipedia.org/wiki/WoW64#Registry_and_file_system) will be checked first for these keys, followed by the \"native\" registry view. Use whichever is appropriate for your application.\n>\n> **For Firefox 63 and older:** This key should _not_ be created under [Wow6432Node](https://en.wikipedia.org/wiki/WoW64#Registry_and_file_system), even if the app is 32-bit. Previous versions of the browser will always look for the key under the \"native\" view of the registry, not the 32-bit emulation. To ensure that the key is created in the \"native\" view, you can pass the `KEY_WOW64_64KEY` or `KEY_WOW64_32KEY` flags into `RegCreateKeyEx`. See [Accessing an Alternate Registry View](https://docs.microsoft.com/windows/win32/winprog64/accessing-an-alternate-registry-view).\n\nFor per-user visibility, create a registry key with the following name:\n\n```plain\nHKEY_CURRENT_USER\\SOFTWARE\\Mozilla\\NativeMessagingHosts\\\n```\n\n```plain\nHKEY_CURRENT_USER\\SOFTWARE\\Mozilla\\ManagedStorage\\\n```\n\n```plain\nHKEY_CURRENT_USER\\SOFTWARE\\Mozilla\\PKCS11Modules\\\n```\n\nThe key should have a single default value, which is the path to the manifest.\n\n### macOS\n\nFor global visibility, store the manifest in:\n\n```plain\n/Library/Application Support/Mozilla/NativeMessagingHosts/.json\n```\n\n```plain\n/Library/Application Support/Mozilla/ManagedStorage/.json\n```\n\n```plain\n/Library/Application Support/Mozilla/PKCS11Modules/.json\n```\n\nFor per-user visibility, store the manifest in:\n\n```plain\n~/Library/Application Support/Mozilla/NativeMessagingHosts/.json\n```\n\n```plain\n~/Library/Application Support/Mozilla/ManagedStorage/.json\n```\n\n```plain\n~/Library/Application Support/Mozilla/PKCS11Modules/.json\n```\n\n### Linux\n\nFor global visibility, store the manifest in either:\n\n```plain\n/usr/lib/mozilla/native-messaging-hosts/.json\n```\n\n```plain\n/usr/lib/mozilla/managed-storage/.json\n```\n\n```plain\n/usr/lib/mozilla/pkcs11-modules/.json\n```\n\nor:\n\n```plain\n/usr/lib64/mozilla/native-messaging-hosts/.json\n```\n\n```plain\n/usr/lib64/mozilla/managed-storage/.json\n```\n\n```plain\n/usr/lib64/mozilla/pkcs11-modules/.json\n```\n\nFor per-user visibility, store the manifest in:\n\n```plain\n~/.mozilla/native-messaging-hosts/.json\n```\n\n```plain\n~/.mozilla/managed-storage/.json\n```\n\n```plain\n~/.mozilla/pkcs11-modules/.json\n```\n"},"__index_level_0__":{"kind":"number","value":0,"string":"0"}}},{"rowIdx":9057,"cells":{"repo_id":{"kind":"string","value":"data/mdn-content/files/en-us/mozilla/add-ons/webextensions"},"file_path":{"kind":"string","value":"data/mdn-content/files/en-us/mozilla/add-ons/webextensions/working_with_the_tabs_api/index.md"},"content":{"kind":"string","value":"---\ntitle: Work with the Tabs API\nslug: Mozilla/Add-ons/WebExtensions/Working_with_the_Tabs_API\npage-type: guide\n---\n\n{{AddonSidebar}}\n\nTabs let a user open several web pages in their browser window and then switch between those web pages. With the Tabs API, you can work with and manipulate these tabs to create utilities that provide users with new ways to work with tabs or to deliver the features of your extension.\n\nIn this how-to article we'll look at:\n\n- Permissions needed to use the Tabs API.\n- Discovering more about tabs and their properties using {{WebExtAPIRef(\"tabs.query\")}}.\n- Creating, duplicating, moving, updating, reloading, and removing tabs.\n- Manipulating a tab's zoom level.\n- Manipulating a tab's CSS.\n\nWe then conclude by looking at some other, miscellaneous features offered by the API.\n\n> **Note:** There are some Tab API features covered elsewhere. These are the methods you can use to manipulate tab content with scripts ({{WebExtAPIRef(\"tabs.connect\")}}, {{WebExtAPIRef(\"tabs.sendMessage\")}}, and {{WebExtAPIRef(\"tabs.executeScript\")}}). If you want more information on these methods, see the Concepts article [Content scripts](/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_scripts) and the how-to guide [Modify a web page](/en-US/docs/Mozilla/Add-ons/WebExtensions/Modify_a_web_page).\n\n## Permissions and the Tabs API\n\nFor the majority of the Tabs API functions you don't need any permissions; however, there are some exceptions:\n\n- `\"tabs\"` permission is needed to access the `Tab.url`, `Tab.title`, and `Tab.favIconUrl` properties of the Tab object. In Firefox, you also need `\"tabs\"` to perform a [query](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs/query) by URL.\n- [Host permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#host_permissions) is needed for {{WebExtAPIRef(\"tabs.executeScript()\")}} or {{WebExtAPIRef(\"tabs.insertCSS()\")}}.\n\nThe following is how you might request `\"tabs\"` permission in your extension's manifest.json file:\n\n```json\n\"permissions\": [\n \"\",\n \"tabs\"\n],\n```\n\nThis request gives you use of all Tabs API feature on all website your user visits. There is also an alternative approach for requesting permissions to use {{WebExtAPIRef(\"tabs.executeScript()\")}} or {{WebExtAPIRef(\"tabs.insertCSS()\")}} where you don't need host permission, in the form of [`\"activeTab\"`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#activetab_permission). This permission provides the same rights as `\"tabs\"` with ``, but with two restrictions:\n\n- the user must interact with the extension through its browser or page action, context menu, or shortcut key.\n- it only grants permission within the active tab.\n\nThe benefit of this approach is the user won't get a permissions warning saying your extension can \"Access your data for all websites\". This is because `` permission gives an extension the ability to execute scripts in any tab, any time it likes, whereas [`\"activeTab\"`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#activetab_permission) is limited to allowing the extension to perform a user requested action in the current tab.\n\n## Discovering more about tabs and their properties\n\nThere will be occasions when you want to get a list of all the tabs in all the browser windows. Other times you might want to find a subset of tabs that match some specific criteria, such as those opened from a specific tab or displaying pages from a particular domain. And once you have your list of tabs, you'll probably want to know more about their properties.\n\nThis is where {{WebExtAPIRef(\"tabs.query()\")}} comes in. Used alone to get all tabs or taking the `queryInfo` object—to specify query criteria such as whether the tab is active, in the current window, or one or more of 17 criteria—{{WebExtAPIRef(\"tabs.query()\")}} returns an array of {{WebExtAPIRef(\"tabs.Tab\")}} objects containing information about the tabs.\n\nWhere you want information about the current tab only, you can get a {{WebExtAPIRef(\"tabs.Tab\")}} object for that tab using {{WebExtAPIRef(\"tabs.getCurrent()\")}}. If you have a tab's ID, you can get its {{WebExtAPIRef(\"tabs.Tab\")}} object using {{WebExtAPIRef(\"tabs.get()\")}}.\n\n### How to example\n\nTo see how {{WebExtAPIRef(\"tabs.query()\")}} and {{WebExtAPIRef(\"tabs.Tab\")}} are used, let's walk through how the [tabs-tabs-tabs](https://github.com/mdn/webextensions-examples/tree/main/tabs-tabs-tabs) example adds the list of \"switch to tabs\" to its toolbar button popup.\n\n![The tabs toolbar menu showing the switch to tap area](switch_to_tab.png)\n\n- manifest.json\n\n - : Here is the [`manifest.json`](https://github.com/mdn/webextensions-examples/blob/main/tabs-tabs-tabs/manifest.json):\n\n ```json\n {\n \"browser_action\": {\n \"default_title\": \"Tabs, tabs, tabs\",\n \"default_popup\": \"tabs.html\"\n },\n \"description\": \"A list of methods you can perform on a tab.\",\n \"homepage_url\": \"https://github.com/mdn/webextensions-examples/tree/main/tabs-tabs-tabs\",\n \"manifest_version\": 2,\n \"name\": \"Tabs, tabs, tabs\",\n \"permissions\": [\"tabs\"],\n \"version\": \"1.0\"\n }\n ```\n\n > **Note:**\n >\n > - **`tabs.html` is defined as the `default_popup` in `browser_action`.** It is displayed whenever the user clicks the extension's toolbar icon.\n > - **Permissions includes tabs.** This is needed to support the tab list feature, as the extension reads the title of the tabs for display in the popup.\n\n- tabs.html\n\n - : `tabs.html` defines the content of the extension's popup:\n\n ```html\n \n \n \n \n \n \n\n \n
\n
\n
Tabs-tabs-tabs
\n
\n\n \n Move active tab to the beginning of the window\n \n
\n\n \n\n
\n

Switch to tab

\n
\n
\n
\n\n \n \n \n ```\n\n This does the following:\n\n 1. The menu items are declared.\n 2. An empty `div` with the ID `tabs-list` is declared to contain the list of tabs.\n 3. `tabs.js` is called.\n\n- tabs.js\n - : In [`tabs.js`](https://github.com/mdn/webextensions-examples/blob/main/tabs-tabs-tabs/tabs.js), we'll see how the list of tabs is built and added to the popup.\n\n#### Creating the popup\n\nFirst, an event handler is added to execute `listTabs()` when `tabs.html` is loaded:\n\n```js\ndocument.addEventListener(\"DOMContentLoaded\", listTabs);\n```\n\nThe first thing that `listTabs()` does is to call `getCurrentWindowTabs()`. This is where {{WebExtAPIRef(\"tabs.query()\")}} is used to get a {{WebExtAPIRef(\"tabs.Tab\")}} object for the tabs in the current window:\n\n```js\nfunction getCurrentWindowTabs() {\n return browser.tabs.query({ currentWindow: true });\n}\n```\n\nNow, `listTabs()` is ready to create the content for the popup.\n\nTo start with:\n\n1. Grab the `
` element.\n2. Create a document fragment (into which the list will be built).\n3. Set counters.\n4. Clear the content of the `
` element.\n\n```js\nfunction listTabs() {\n getCurrentWindowTabs().then((tabs) => {\n const tabsList = document.getElementById('tabs-list');\n const currentTabs = document.createDocumentFragment();\n const limit = 5;\n let counter = 0;\n\n tabsList.textContent = '';\n```\n\nNext, we'll create the links for each tab:\n\n1. Loops through the first 5 items from the {{WebExtAPIRef(\"tabs.Tab\")}} object.\n2. For each item, add a hyperlink to the document fragment.\n\n - The link's label—that is, its text—is set using the tab's `title` (or the `id`, if it has no `title`).\n - The link's address is set using the tab's `id`.\n\n```js\nfor (const tab of tabs) {\n if (!tab.active && counter <= limit) {\n const tabLink = document.createElement(\"a\");\n\n tabLink.textContent = tab.title || tab.id;\n\n tabLink.setAttribute(\"href\", tab.id);\n tabLink.classList.add(\"switch-tabs\");\n currentTabs.appendChild(tabLink);\n }\n\n counter += 1;\n}\n```\n\nFinally, the document fragment is written to the `
` element:\n\n```js\n tabsList.appendChild(currentTabs);\n });\n}\n```\n\n#### Working with the active tab\n\nAnother related example feature is the \"Alert active tab\" info option that dumps all the {{WebExtAPIRef(\"tabs.Tab\")}} object properties for the active tab into an alert:\n\n```js\nelse if (e.target.id === \"tabs-alertinfo\") {\n callOnActiveTab((tab) => {\n let props = \"\";\n for (const item in tab) {\n props += `${ item } = ${ tab[item] } \\n`;\n }\n alert(props);\n });\n}\n```\n\nWhere `callOnActiveTab()` finds the active tab object by looping through the {{WebExtAPIRef(\"tabs.Tab\")}} objects looking for the item with active set:\n\n```js\ndocument.addEventListener(\"click\", (e) => {\n function callOnActiveTab(callback) {\n getCurrentWindowTabs().then((tabs) => {\n for (const tab of tabs) {\n if (tab.active) {\n callback(tab, tabs);\n }\n }\n });\n }\n}\n```\n\n## Creating, duplicating, moving, updating, reloading, and removing tabs\n\nHaving gathered information about the tabs you'll most likely want to do something with them—either to offer users features for manipulating and managing tabs or to implement functionality in your extension.\n\nThe following functions are available:\n\n- create a new tab ({{WebExtAPIRef(\"tabs.create()\")}}).\n- duplicate a tab ({{WebExtAPIRef(\"tabs.duplicate()\")}}).\n- remove a tab ({{WebExtAPIRef(\"tabs.remove()\")}}).\n- move a tab ({{WebExtAPIRef(\"tabs.move()\")}}).\n- update the tab's URL—effectively browse to a new page—({{WebExtAPIRef(\"tabs.update()\")}}).\n- reload the tab's page ({{WebExtAPIRef(\"tabs.reload()\")}}).\n\n> **Note:** These functions all require the ID (or IDs) of the tab they are manipulating:\n>\n> - {{WebExtAPIRef(\"tabs.duplicate()\")}}\n> - {{WebExtAPIRef(\"tabs.remove()\")}}\n> - {{WebExtAPIRef(\"tabs.move()\")}}\n>\n> Whereas the following functions will act on the active tab (if no tab `id` is provided):\n>\n> - {{WebExtAPIRef(\"tabs.update()\")}}\n> - {{WebExtAPIRef(\"tabs.reload()\")}}\n\n### How to example\n\nThe [tabs-tabs-tabs](https://github.com/mdn/webextensions-examples/tree/main/tabs-tabs-tabs) example exercises all of these features except for updating a tab's URL The way in which these APIs are used is similar, so we'll look at one of the more involved implementations, that of the \"Move active tab to the beginning of the window list\" option.\n\nBut first, here is a demonstration of the feature in action:\n\n{{EmbedYouTube(\"-lJRzTIvhxo\")}}\n\n- manifest.json\n - : None of the functions require a permission to operate, so there are no features in the [manifest.json](https://github.com/mdn/webextensions-examples/blob/main/tabs-tabs-tabs/manifest.json) file that need to be highlighted.\n- tabs.html\n\n - : [`tabs.html`](https://github.com/mdn/webextensions-examples/blob/main/tabs-tabs-tabs/tabs.html) defines the \"menu\" displayed in the popup, which includes the \"Move active tab to the beginning of the window list\" option, with a series of `` tags grouped by a visual separator. Each menu item is given an `id`, which is used in `tabs.js` to determine which menu item is being requested.\n\n ```html\n \n Move active tab to the beginning of the window\n \n
\n Move active tab to the end of the window\n
\n\n
\n\n Duplicate active tab
\n Reload active tab
\n Alert active tab info
\n ```\n\n- tabs.js\n\n - : To implement the \"menu\" defined in `tabs.html`, [`tabs.js`](https://github.com/mdn/webextensions-examples/blob/main/tabs-tabs-tabs/tabs.js) includes a listener for clicks in `tabs.html`:\n\n ```js\n document.addEventListener(\"click\", (e) => {\n function callOnActiveTab(callback) {\n getCurrentWindowTabs().then((tabs) => {\n for (const tab of tabs) {\n if (tab.active) {\n callback(tab, tabs);\n }\n }\n });\n }\n });\n ```\n\n A series of `if` statements then look to match the `id` of the item clicked.\n\n This code snippet is for the \"Move active tab to the beginning of the window list\" option:\n\n ```js\n if (e.target.id === \"tabs-move-beginning\") {\n callOnActiveTab((tab, tabs) => {\n let index = 0;\n if (!tab.pinned) {\n index = firstUnpinnedTab(tabs);\n }\n console.log(`moving ${tab.id} to ${index}`);\n browser.tabs.move([tab.id], { index });\n });\n }\n ```\n\n It's worth noting the use of `console.log()`. This enables you to output information to the [debugger](https://extensionworkshop.com/documentation/develop/debugging/) console, which can be useful when resolving issues found during development.\n\n ![Example of the console.log output, from the move tabs feature, in the debugging console](console.png)\n\n The move code first calls `callOnActiveTab()` which in turn calls `getCurrentWindowTabs()` to get a {{WebExtAPIRef(\"tabs.Tab\")}} object containing the active window's tabs. It then loops through the object to find and return the active tab object:\n\n ```js\n function callOnActiveTab(callback) {\n getCurrentWindowTabs().then((tabs) => {\n for (const tab of tabs) {\n if (tab.active) {\n callback(tab, tabs);\n }\n }\n });\n }\n ```\n\n#### Pinned tabs\n\nA feature of tabs is that the user can _pin_ tabs in a window. Pinned tabs are placed at the start of the tab list and cannot be moved. This means that the earliest position a tab can move to is the first position after any pinned tabs. So, `firstUnpinnedTab()` is called to find the position of the first unpinned tab by looping through the `tabs` object:\n\n```js\nfunction firstUnpinnedTab(tabs) {\n for (const tab of tabs) {\n if (!tab.pinned) {\n return tab.index;\n }\n }\n}\n```\n\nWe now have everything needed to move the tab: the active tab object from which we can get the tab `id` and the position the tab is to be moved to. So, we can implement the move:\n\n```js\nbrowser.tabs.move([tab.id], { index });\n```\n\nThe remaining functions to duplicate, reload, create, and remove tabs are implemented similarly.\n\n## Manipulating a tab's zoom level\n\nThe next set of functions enable you to get ({{WebExtAPIRef(\"tabs.getZoom\")}}) and set ({{WebExtAPIRef(\"tabs.setZoom\")}}) the zoom level within a tab. You can also retrieve the zoom settings ({{WebExtAPIRef(\"tabs.getZoomSettings\")}}) but, at the time of writing, the ability to set the settings ({{WebExtAPIRef(\"tabs.setZoomSettings\")}}) wasn't available in Firefox.\n\nThe level of zoom can be between 30% and 500% (represented as decimals `0.3` to `5`).\n\nIn Firefox the default zoom settings are:\n\n- **default zoom level:** 100%.\n- **zoom mode:** automatic (so the browser manages how zoom levels are set).\n- **scope of zoom changes:** `\"per-origin\"`, meaning that when you visit a site again, it takes the zoom level set in your last visit.\n\n### How to example\n\nThe [tabs-tabs-tabs](https://github.com/mdn/webextensions-examples/tree/main/tabs-tabs-tabs) example includes three demonstrations of the zoom feature: zoom in, zoom out, and reset zoom. Here is the feature in action:\n\n{{EmbedYouTube(\"RFr3oYBCg28\")}}\n\nLet's take a look at how the zoom in is implemented.\n\n- manifest.json\n - : None of the zoom functions require permissions, so there are no features in the [manifest.json](https://github.com/mdn/webextensions-examples/blob/main/tabs-tabs-tabs/manifest.json) file that need to be highlighted.\n- tabs.html\n - : We have already discussed how the [`tabs.html`](https://github.com/mdn/webextensions-examples/blob/main/tabs-tabs-tabs/tabs.html) defines the options for this extension, nothing new or unique is done to provide the zoom options.\n- tabs.js\n\n - : [`tabs.js`](https://github.com/mdn/webextensions-examples/blob/main/tabs-tabs-tabs/tabs.js) starts by defining several constants used in the zoom code:\n\n ```js\n const ZOOM_INCREMENT = 0.2;\n const MAX_ZOOM = 5;\n const MIN_ZOOM = 0.3;\n const DEFAULT_ZOOM = 1;\n ```\n\n It then uses the same listener we discussed earlier so it can act on clicks in `tabs.html`.\n\n For the zoom in feature, this runs:\n\n ```js\n else if (e.target.id === \"tabs-add-zoom\") {\n callOnActiveTab((tab) => {\n browser.tabs.getZoom(tab.id).then((zoomFactor) => {\n //the maximum zoomFactor is 5, it can't go higher\n if (zoomFactor >= MAX_ZOOM) {\n alert(\"Tab zoom factor is already at max!\");\n } else {\n let newZoomFactor = zoomFactor + ZOOM_INCREMENT;\n //if the newZoomFactor is set to higher than the max accepted\n //it won't change, and will never alert that it's at maximum\n newZoomFactor = newZoomFactor > MAX_ZOOM ? MAX_ZOOM : newZoomFactor;\n browser.tabs.setZoom(tab.id, newZoomFactor);\n }\n });\n });\n }\n ```\n\n This code uses `callOnActiveTab()` to get the details of the active tab, then {{WebExtAPIRef(\"tabs.getZoom\")}} gets the tab's current zoom factor. The current zoom is compared to the defined maximum (`MAX_ZOOM`) and an alert issued if the tab is already at the maximum zoom. Otherwise, the zoom level is incremented but limited to the maximum zoom, then the zoom is set with {{WebExtAPIRef(\"tabs.getZoom\")}}.\n\n## Manipulating a tab's CSS\n\nAnother significant capability offered by the Tabs API is the ability to manipulate the CSS within a tab—add new CSS to a tab ({{WebExtAPIRef(\"tabs.insertCSS()\")}}) or remove CSS from a tab ({{WebExtAPIRef(\"tabs.removeCSS()\")}}).\n\nThis can be useful, for example, if you want to highlight certain page elements or change the default layout of the page.\n\n### How to example\n\nThe [apply-css](https://github.com/mdn/webextensions-examples/tree/main/apply-css) example uses these features to add a red border to the web page in the active tab. Here is the feature in action:\n\n{{EmbedYouTube(\"bcK-GT2Dyhs\")}}\n\nLet's walk through how it's set up.\n\n- manifest.json\n\n - : The [`manifest.json`](https://github.com/mdn/webextensions-examples/blob/main/apply-css/manifest.json) requests permissions required to use the CSS features. You need either:\n\n - `\"tabs\"` permission and [host permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#host_permissions); or,\n - `\"activeTab\"` permission.\n\n The latter is the most useful, as it allows an extension to use {{WebExtAPIRef(\"tabs.insertCSS()\")}} and {{WebExtAPIRef(\"tabs.removeCSS()\")}} in the active tab when run from the extension's browser or page action, context menu, or a shortcut.\n\n ```json\n {\n \"description\": \"Adds a page action to toggle applying CSS to pages.\",\n\n \"manifest_version\": 2,\n \"name\": \"apply-css\",\n \"version\": \"1.0\",\n \"homepage_url\": \"https://github.com/mdn/webextensions-examples/tree/main/apply-css\",\n\n \"background\": {\n \"scripts\": [\"background.js\"]\n },\n\n \"page_action\": {\n \"default_icon\": \"icons/off.svg\"\n },\n\n \"permissions\": [\"activeTab\", \"tabs\"]\n }\n ```\n\n You will note that `\"tabs\"` permission is requested in addition to `\"activeTab\"`. This additional permission is needed to enable the extension's script to access the tab's URL, the importance of which we'll see in a moment.\n\n The other main features in the manifest.json file are the definition of:\n\n - **a background script**, which starts running as soon as the extension is loaded.\n - **a \"page action\"**, which defines an icon to be added to the browser's address bar.\n\n- background.js\n\n - : On startup, [`background.js`](https://github.com/mdn/webextensions-examples/blob/main/apply-css/background.js) sets some constants to define the CSS to be applied, titles for the \"page action\", and a list of protocols the extension will work in:\n\n ```js\n const CSS = \"body { border: 20px solid red; }\";\n const TITLE_APPLY = \"Apply CSS\";\n const TITLE_REMOVE = \"Remove CSS\";\n const APPLICABLE_PROTOCOLS = [\"http:\", \"https:\"];\n ```\n\n When first loaded, the extension uses {{WebExtAPIRef(\"tabs.query()\")}} to get a list of all the tabs in the current browser window. It then loops through the tabs calling `initializePageAction()`.\n\n ```js\n browser.tabs.query({}).then((tabs) => {\n for (const tab of tabs) {\n initializePageAction(tab);\n }\n });\n ```\n\n `initializePageAction` uses `protocolIsApplicable()` to determine whether the active tab's URL is one the CSS can be applied to:\n\n ```js\n function protocolIsApplicable(url) {\n const anchor = document.createElement(\"a\");\n anchor.href = url;\n return APPLICABLE_PROTOCOLS.includes(anchor.protocol);\n }\n ```\n\n Then, if the example can act on the tab, `initializePageAction()` sets the tab's `pageAction` (navigation bar) icon and title to use the \"off\" versions before making the `pageAction` visible:\n\n ```js\n function initializePageAction(tab) {\n if (protocolIsApplicable(tab.url)) {\n browser.pageAction.setIcon({ tabId: tab.id, path: \"icons/off.svg\" });\n browser.pageAction.setTitle({ tabId: tab.id, title: TITLE_APPLY });\n browser.pageAction.show(tab.id);\n }\n }\n ```\n\n Next, a listener on `pageAction.onClicked` waits for the `pageAction` icon to be clicked, and calls `toggleCSS` when it is.\n\n ```js\n browser.pageAction.onClicked.addListener(toggleCSS);\n ```\n\n `toggleCSS()` gets the title of the `pageAction` and then takes the action described:\n\n - **For \"Apply CSS\":**\n\n - toggles the `pageAction` icon and title to the \"remove\" versions.\n - applies the CSS using {{WebExtAPIRef(\"tabs.insertCSS()\")}}.\n\n - **For \"Remove CSS\":**\n\n - toggles the `pageAction` icon and title to the \"apply\" versions.\n - removes the CSS using {{WebExtAPIRef(\"tabs.removeCSS()\")}}.\n\n ```js\n function toggleCSS(tab) {\n function gotTitle(title) {\n if (title === TITLE_APPLY) {\n browser.pageAction.setIcon({ tabId: tab.id, path: \"icons/on.svg\" });\n browser.pageAction.setTitle({ tabId: tab.id, title: TITLE_REMOVE });\n browser.tabs.insertCSS({ code: CSS });\n } else {\n browser.pageAction.setIcon({ tabId: tab.id, path: \"icons/off.svg\" });\n browser.pageAction.setTitle({ tabId: tab.id, title: TITLE_APPLY });\n browser.tabs.removeCSS({ code: CSS });\n }\n }\n\n browser.pageAction.getTitle({ tabId: tab.id }).then(gotTitle);\n }\n ```\n\n Finally, to ensure that the `pageAction` is valid after each update to the tab, a listener on {{WebExtAPIRef(\"tabs.onUpdated\")}} calls `initializePageAction()` each time the tab is updated to check that the tab is still using a protocol to which the CSS can be applied.\n\n ```js\n browser.tabs.onUpdated.addListener((id, changeInfo, tab) => {\n initializePageAction(tab);\n });\n ```\n\n## Some other interesting abilities\n\nThere are a couple of other Tabs API features that don't fit into one of the earlier sections:\n\n- Capture the visible tab content with {{WebExtAPIRef(\"tabs.captureVisibleTab\")}}.\n- Detect the primary language of the content in a tab using {{WebExtAPIRef(\"tabs.detectLanguage\")}}. This could be used, for example, to match the language in your extension's UI with that of the page it's running in.\n\n## Learn more\n\nIf you want to learn more about the Tabs API, check out:\n\n- [Tabs API reference](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs)\n- [Example extensions](/en-US/docs/Mozilla/Add-ons/WebExtensions/Examples) (many of which use the Tabs API)\n"},"__index_level_0__":{"kind":"number","value":0,"string":"0"}}},{"rowIdx":9058,"cells":{"repo_id":{"kind":"string","value":"data/mdn-content/files/en-us/mozilla/add-ons/webextensions"},"file_path":{"kind":"string","value":"data/mdn-content/files/en-us/mozilla/add-ons/webextensions/match_patterns/index.md"},"content":{"kind":"string","value":"---\ntitle: Match patterns\nslug: Mozilla/Add-ons/WebExtensions/Match_patterns\npage-type: guide\nbrowser-compat: webextensions.match_patterns.scheme\n---\n\n{{AddonSidebar}}\n\nMatch patterns are a way to specify groups of URLs: a match pattern matches a specific set of URLs. They are used in WebExtensions APIs in a few places, most notably to specify which documents to load [content scripts](/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_scripts) into, and to specify which URLs to add [`webRequest`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/webRequest) listeners to.\n\nAPIs that use match patterns usually accept a list of match patterns, and will perform the appropriate action if the URL matches any of the patterns. See, for example, the [`content_scripts`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/content_scripts) key in manifest.json.\n\n## Match pattern structure\n\n> **Note:** Some browsers don't support certain schemes.\n> Check the [Browser compatibility table](#browser_compatibility) for details.\n\nAll match patterns are specified as strings. Apart from the special [``](#all_urls) pattern, match patterns consist of three parts: _scheme_, _host_, and _path_. The scheme and host are separated by `://`.\n\n```plain\n://\n```\n\n### scheme\n\nThe _scheme_ component may take one of two forms:\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
FormMatches
*\n Only \"http\" and \"https\" and in some browsers also\n \"ws\" and \"wss\".\n
\n One of http, https, ws,\n wss, ftp, data,\n file, or (chrome-)extension.\n Only the given scheme.
\n\n### host\n\nThe _host_ component may take one of three forms:\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
FormMatches
*Any host.
*. followed by part of the hostname.The given host and any of its subdomains.
A complete hostname, without wildcards.Only the given host.
\n\n_host_ must not include a port number.\n\n_host_ is optional only if the _scheme_ is \"file\".\n\nNote that the wildcard may only appear at the start.\n\n### path\n\nThe _path_ component must begin with a `/`.\n\nAfter that, it may subsequently contain any combination of the `*` wildcard and any of the characters that are allowed in URL paths or query strings. Unlike _host_, the _path_ component may contain the `*` wildcard in the middle or at the end, and the `*` wildcard may appear more than once.\n\nThe value for the _path_ matches against the string which is the URL path plus the [URL query string](https://en.wikipedia.org/wiki/Query_string). This includes the `?` between the two, if the query string is present in the URL. For example, if you want to match URLs on any domain where the URL path ends with `foo.bar`, then you need to use an array of Match Patterns like `['*://*/*foo.bar', '*://*/*foo.bar?*']`. The `?*` is needed, rather than just `bar*`, in order to anchor the ending `*` as applying to the URL query string and not some portion of the URL path.\n\nNeither the [URL fragment identifier](https://en.wikipedia.org/wiki/Fragment_identifier), nor the `#` which precedes it, are considered as part of the _path_.\n\n> **Note:** The path pattern string should not include a port number. Adding a port, as in: `http://localhost:1234/*` causes the match pattern to be ignored. However, `http://localhost:1234` will match with `http://localhost/*`.\n\n### \\\n\nThe special value `` matches all URLs under any of the supported schemes: that is \"http\", \"https\", \"ws\", \"wss\", \"ftp\", \"data\", and \"file\".\n\n## Examples\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
PatternExample matchesExample non-matches
\n

&#x3C;all_urls>

\n

Match all URLs.

\n
\n

http://example.org/

\n

https://a.org/some/path/

\n

ws://sockets.somewhere.org/

\n

wss://ws.example.com/stuff/

\n

ftp://files.somewhere.org/

\n
\n

resource://a/b/c/
(unsupported scheme)

\n

\n ftps://files.somewhere.org/
(unsupported scheme)\n

\n
\n

*://*/*

\n

Match all HTTP, HTTPS and WebSocket URLs.

\n
\n

http://example.org/

\n

https://a.org/some/path/

\n

ws://sockets.somewhere.org/

\n

wss://ws.example.com/stuff/

\n
\n

ftp://ftp.example.org/
(unmatched scheme)

\n

file:///a/
(unmatched scheme)

\n
\n

*://*.mozilla.org/*

\n

\n Match all HTTP, HTTPS and WebSocket URLs that are hosted at\n \"mozilla.org\" or one of its subdomains.\n

\n
\n

http://mozilla.org/

\n

https://mozilla.org/

\n

http://a.mozilla.org/

\n

http://a.b.mozilla.org/

\n

https://b.mozilla.org/path/

\n

ws://ws.mozilla.org/

\n

wss://secure.mozilla.org/something

\n
\n

ftp://mozilla.org/
(unmatched scheme)

\n

http://mozilla.com/
(unmatched host)

\n

http://firefox.org/
(unmatched host)

\n
\n

*://mozilla.org/

\n

\n Match all HTTP, HTTPS and WebSocket URLs that are hosted at exactly\n \"mozilla.org/\".\n

\n
\n

http://mozilla.org/

\n

https://mozilla.org/

\n

ws://mozilla.org/

\n

wss://mozilla.org/

\n
\n

ftp://mozilla.org/
(unmatched scheme)

\n

http://a.mozilla.org/
(unmatched host)

\n

http://mozilla.org/a
(unmatched path)

\n
\n

ftp://mozilla.org/

\n

Match only \"ftp://mozilla.org/\".

\n
ftp://mozilla.org\n

http://mozilla.org/
(unmatched scheme)

\n

ftp://sub.mozilla.org/
(unmatched host)

\n

ftp://mozilla.org/path
(unmatched path)

\n
\n

https://*/path

\n

Match HTTPS URLs on any host, whose path is \"path\".

\n
\n

https://mozilla.org/path

\n

https://a.mozilla.org/path

\n

https://something.com/path

\n
\n

http://mozilla.org/path
(unmatched scheme)

\n

https://mozilla.org/path/
(unmatched path)

\n

https://mozilla.org/a
(unmatched path)

\n

https://mozilla.org/
(unmatched path)

\n

\n https://mozilla.org/path?foo=1
(unmatched path due\n to URL query string)\n

\n
\n

https://*/path/

\n

\n Match HTTPS URLs on any host, whose path is \"path/\" and which has no\n URL query string.\n

\n
\n

https://mozilla.org/path/

\n

https://a.mozilla.org/path/

\n

https://something.com/path/

\n
\n

http://mozilla.org/path/
(unmatched scheme)

\n

https://mozilla.org/path
(unmatched path)

\n

https://mozilla.org/a
(unmatched path)

\n

https://mozilla.org/
(unmatched path)

\n

\n https://mozilla.org/path/?foo=1
(unmatched path due to URL query string)\n

\n
\n

https://mozilla.org/*

\n

\n Match HTTPS URLs only at \"mozilla.org\", with any URL path and URL\n query string.\n

\n
\n

https://mozilla.org/

\n

https://mozilla.org/path

\n

https://mozilla.org/another

\n

https://mozilla.org/path/to/doc

\n

https://mozilla.org/path/to/doc?foo=1

\n
\n

http://mozilla.org/path
(unmatched scheme)

\n

https://mozilla.com/path
(unmatched host)

\n
\n

https://mozilla.org/a/b/c/

\n

Match only this URL, or this URL with any URL fragment.

\n
\n

https://mozilla.org/a/b/c/

\n

https://mozilla.org/a/b/c/#section1

\n
Anything else.
\n

https://mozilla.org/*/b/*/

\n

\n Match HTTPS URLs hosted on \"mozilla.org\", whose path contains a\n component \"b\" somewhere in the middle. Will match URLs with query\n strings, if the string ends in a /.\n

\n
\n

https://mozilla.org/a/b/c/

\n

https://mozilla.org/d/b/f/

\n

https://mozilla.org/a/b/c/d/

\n

https://mozilla.org/a/b/c/d/#section1

\n

https://mozilla.org/a/b/c/d/?foo=/

\n

\n https://mozilla.org/a?foo=21314&#x26;bar=/b/&#x26;extra=c/\n

\n
\n

https://mozilla.org/b/*/
(unmatched path)

\n

https://mozilla.org/a/b/
(unmatched path)

\n

\n https://mozilla.org/a/b/c/d/?foo=bar
(unmatched path\n due to URL query string)\n

\n
\n

file:///blah/*

\n

Match any FILE URL whose path begins with \"blah\".

\n
\n

file:///blah/

\n

file:///blah/bleh

\n
file:///bleh/
(unmatched path)
\n\n### Invalid match patterns\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
Invalid patternReason
resource://path/Unsupported scheme.
https://mozilla.orgNo path.
https://mozilla.*.org/\"*\" in host must be at the start.
https://*zilla.org/\"*\" in host must be the only character or be followed by \".\".
http*://mozilla.org/\"*\" in scheme must be the only character.
https://mozilla.org:80/Host must not include a port number.
*://*Empty path: this should be \"*://*/*\".
file://*Empty path: this should be \"file:///*\".
\n\n## Browser compatibility\n\n{{Compat}}\n"},"__index_level_0__":{"kind":"number","value":0,"string":"0"}}},{"rowIdx":9059,"cells":{"repo_id":{"kind":"string","value":"data/mdn-content/files/en-us/mozilla/add-ons/webextensions"},"file_path":{"kind":"string","value":"data/mdn-content/files/en-us/mozilla/add-ons/webextensions/working_with_files/index.md"},"content":{"kind":"string","value":"---\ntitle: Work with files\nslug: Mozilla/Add-ons/WebExtensions/Working_with_files\npage-type: guide\n---\n\n{{AddonSidebar}}\n\nYour browser extension may need to work with files to deliver its full functionality. This article looks at the five mechanisms you have for handling files:\n\n- Downloading files to the user's selected download folder.\n- Opening files using a file picker on a web page.\n- Opening files using drag and drop onto a web page.\n- Storing files or blobs locally with IndexedDB using the idb-file-storage library.\n- Passing files to a native application on the user's computer.\n\nFor each of these mechanisms, we introduce their use with references to the relevant API documentation, guides, and any examples that show how to use the API.\n\n## Download files using the downloads API\n\nThis mechanism enables you to get a file from your website (or any location you can define as a URL) to the user's computer. The key method is {{WebExtAPIRef(\"downloads.download()\")}}, which in its simplest form accepts a URL and downloads the file from that URL to the user's default downloads folder:\n\n```js\nbrowser.downloads.download({ url: \"https://example.org/image.png\" });\n```\n\nYou can let the user download to a location of their choice by specifying the `saveAs` parameter.\n\n> **Note:** Using [URL.createObjectURL()](/en-US/docs/Web/API/URL/createObjectURL_static) you can also download files and blobs defined in your JavaScript, which can include local content retrieved from IndexedDB.\n\nThe downloads API also provides features to cancel, pause, resume, erase, and remove downloads; search for downloaded files in the download manager; show downloaded files in the computer's file manager; and open a file in an associated application.\n\nTo use this API, you need to have the `\"downloads\"` [API permission](/en-US/docs/Web/API/Permissions#api_permissions) specified in your [`manifest.json`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json) file.\n\nExample: [Latest download](https://github.com/mdn/webextensions-examples/tree/main/latest-download)\nAPI reference: [downloads API](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/downloads)\n\n## Open files in an extension using a file picker\n\nIf you want to work with a file from the user's computer one option is to let the user select a file using the computer's file browser. Either create a new page or inject code into an existing page to use the `file` type of the HTML `input` element to offer the user a file picker. Once the user has picked a file or files, the script associated with the page can access the content of the file using the [DOM File API](/en-US/docs/Web/API/File), in the same way a web application does.\n\nExample: [Imagify](https://github.com/mdn/webextensions-examples/tree/main/imagify)\nGuide: [Using files from web applications](/en-US/docs/Web/API/File_API/Using_files_from_web_applications)\nAPI references: [HTML input element](/en-US/docs/Web/HTML/Element/input/file) | [DOM File API](/en-US/docs/Web/API/File)\n\n> **Note:** If you want to access or process all the files in a selected folder, you can do so using `` to select the folder and return all the files it contains.\n\n## Open files in an extension using drag and drop\n\nThe Web Drag and Drop API offers an alternative to using a file picker. To use this method, establish a 'drop zone' that fits with your UI, then add listeners for the [`dragenter`](/en-US/docs/Web/API/HTMLElement/dragenter_event), [`dragover`](/en-US/docs/Web/API/HTMLElement/dragover_event), and [`drop`](/en-US/docs/Web/API/HTMLElement/drop_event) events to the element. In the handler for the drop event, your code can access any file dropped by the user from the object offered by the `dataTransfer` property using [`DataTransfer.files`](/en-US/docs/Web/API/DataTransfer/files). Your code can then access and manipulate the files using the [DOM File API](/en-US/docs/Web/API/File).\n\nExample: [Imagify](https://github.com/mdn/webextensions-examples/tree/main/imagify)\nGuides: [Using files from web applications](/en-US/docs/Web/API/File_API/Using_files_from_web_applications) | [File drag and drop](/en-US/docs/Web/API/HTML_Drag_and_Drop_API/File_drag_and_drop)\nAPI references: [DOM File API](/en-US/docs/Web/API/File)\n\n## Store files data locally using the IndexedDB file storage library\n\nIf your extension needs to save files locally, the [idb-file-storage library](https://www.npmjs.com/package/idb-file-storage) provides a simple Promise-based wrapper to the [IndexedDB API](/en-US/docs/Web/API/IndexedDB_API) to aid the storage and retrieval of files and blobs.\n\nThe key features of the library are:\n\n- [getFileStorage](https://rpl.github.io/idb-file-storage/function/index.html#static-function-getFileStorage)\n - : Returns an `IDBFileStorage` instance, creating the named storage if it does not exist.\n- [IDBFileStorage](https://rpl.github.io/idb-file-storage/class/src/idb-file-storage.js~IDBFileStorage.html)\n\n - : Provides the methods to save and retrieve files, such as:\n\n - list to obtain an optionally filtered list of file in the database.\n - put to add a file or blob to the database.\n - get to retrieve a file or blob from the database.\n - remove to delete a file or blob from the database.\n\nThe [Store Collected Images](https://github.com/mdn/webextensions-examples/tree/main/store-collected-images/webextension-plain) example illustrates how to use most of these features.\n\nThe Store Collected Images example lets users add images to a collection using an option on the image context menu. Selected images are collected in a popup and can be saved to a named collection. A toolbar button ({{WebExtAPIRef(\"browserAction\")}}) opens a navigate collection page, on which the user can view and delete saved images, with a filter option to narrow choices. [See the example in action](https://www.youtube.com/watch?v=t6aVqMMe2Rc&ab_channel=LucaGreco).\n\nThe workings of the library can be understood by viewing [image-store.js](https://github.com/mdn/webextensions-examples/blob/main/store-collected-images/webextension-plain/utils/image-store.js) in /utils/:\n\n### Creating the store and saving the images\n\n```js\nasync function saveCollectedBlobs(collectionName, collectedBlobs) {\n const storedImages = await getFileStorage({ name: \"stored-images\" });\n\n for (const item of collectedBlobs) {\n await storedImages.put(`${collectionName}/${item.uuid}`, item.blob);\n }\n}\n```\n\n`saveCollectedBlobs` is called when the user clicks save in the popup and has provided a name for the image collection.\n\nFirst, `getFileStorage` creates, if it does not exist already, or retrieves the IndexedDB database `\"stored-images\"` to the object `storedImages`. `storedImages.put()` then adds each collected image to the database, under the collection name, using the blob's unique id (the file name).\n\nIf the image being stored has the same name as one already in the database, it is overwritten. If you want to avoid this, query the database first using `imagesStore.list()` with a filter for the file name; and, if the list returns a file, add a suitable suffix to the name of the new image to store a separate item.\n\n### Retrieving stored images for display\n\n```js\nexport async function loadStoredImages(filter) {\n const imagesStore = await getFileStorage({ name: \"stored-images\" });\n let listOptions = filter ? { includes: filter } : undefined;\n const imagesList = await imagesStore.list(listOptions);\n let storedImages = [];\n for (const storedName of imagesList) {\n const blob = await imagesStore.get(storedName);\n storedImages.push({ storedName, blobUrl: URL.createObjectURL(blob) });\n }\n return storedImages;\n}\n```\n\n`loadStoredImages()` is called when the user clicks view or reload in the navigate collection page. `getFileStorage()` opens the `\"stored-images\"` database, then `imagesStore.list()` gets a filtered list of the stored images. This list is then used to retrieve images with `imagesStore.get()` and build a list to return to the UI.\n\nNote the use of [`URL.createObjectURL(blob)`](/en-US/docs/Web/API/URL/createObjectURL_static) to create a URL that references the image blob. This URL is then used in the UI ([navigate-collection.js](https://github.com/mdn/webextensions-examples/blob/main/store-collected-images/webextension-plain/navigate-collection.js)) to display the image.\n\n### Delete collected images\n\n```js\nasync function removeStoredImages(storedImages) {\n const imagesStore = await getFileStorage({ name: \"stored-images\" });\n for (const storedImage of storedImages) {\n URL.revokeObjectURL(storedImage.blobUrl);\n await imagesStore.remove(storedImage.storedName);\n }\n}\n```\n\n`removeStoredImages()` is called when the user clicks delete in the navigate collection page. Again, `getFileStorage()` opens the `\"stored-images\"` database then `imagesStore.remove()` removes each image from the filtered list of images.\n\nNote the use of [`URL.revokeObjectURL()`](/en-US/docs/Web/API/URL/revokeObjectURL_static) to explicitly revoke the blob URL. This enables the garbage collector to free the memory allocated to the URL. If this is not done, the memory will not get returned until the page on which it was created is closed. If the URL was created in an extension's background page, this is not unloaded until the extension is disabled, uninstalled, or reloaded, so holding this memory unnecessarily could affect browser performance. If the URL is created in an extension's page (new tab, popup, or sidebar) the memory is released when the page is closed, but it is still a good practice to revoke the URL when it is no longer needed.\n\nOnce the blob URL has been revoked, any attempt to load it will result in an error. For example, if the blob URL was used as the `SRC` attribute of an `IMG` tag, the image will not load and will not be visible. It is therefore good practice to remove any revoked blob URLs from generated HTML elements when the blob URL is revoked.\n\nExample: [Store Collected Images](https://github.com/mdn/webextensions-examples/tree/main/store-collected-images/webextension-plain)\nAPI References: [idb-file-storage library](https://rpl.github.io/idb-file-storage/)\n\n> **Note:** You can also use the full Web [IndexedDB API](/en-US/docs/Web/API/IndexedDB_API) to store data from your extension. This can be useful where you need to store data that isn't handled well by the simple key/value pairs offered by the DOM [Storage API](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/storage).\n\n## Process files in a local app\n\nWhere you have a native app or want to deliver additional native features for file processing, use native messaging to pass a file to a native app for processing.\n\nYou have two options:\n\n- Connection-based messaging\n - : Here you trigger the process with `runtime.connectNative()`, which returns a [`runtime.Port`](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/runtime/Port) object. You can then pass a JSON message to the native application using the `postMessage()` function of `Port`. Using the `onMessage.addListener()` function of `Port` you can listen for messages from the native application. The native application is opened if it is not running when `runtime.connectNative()` is called and the application remains running until the extension calls `Port.disconnect()` or the page that connected to it is closed.\n- Connectionless messaging\n - : Here you use `runtime.sendNativeMessage()` to send a JSON message to a new, temporary instance of the native application. The browser closes the native application after receiving any message back from the native application.\n\nTo add the file or blob you want the native application to process use [`JSON.stringify()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify).\n\nTo use this method the extension must request the `\"nativeMessaging\"` [permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions) or [optional permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/optional_permissions) in its `manifest.json` file. Where optional permission is used, remember to check that permission has being granted and where necessary request permission from the user with the {{WebExtAPIRef(\"permissions\")}} API. Reciprocally, the native application must grant permission for the extension by including its ID in the `\"allowed_extensions\"` field of the app manifest.\n\nExample: [Native Messaging](https://github.com/mdn/webextensions-examples/tree/main/native-messaging) (illustrates simple messaging only)\nGuides: [Native messaging](/en-US/docs/Mozilla/Add-ons/WebExtensions/Native_messaging)\nAPI references: [runtime API](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/runtime)\n"},"__index_level_0__":{"kind":"number","value":0,"string":"0"}}},{"rowIdx":9060,"cells":{"repo_id":{"kind":"string","value":"data/mdn-content/files/en-us/mozilla/add-ons/webextensions"},"file_path":{"kind":"string","value":"data/mdn-content/files/en-us/mozilla/add-ons/webextensions/firefox_workflow_overview/index.md"},"content":{"kind":"string","value":"---\ntitle: Firefox workflow overview\nslug: Mozilla/Add-ons/WebExtensions/Firefox_workflow_overview\npage-type: guide\n---\n\n{{AddonSidebar}}\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
\n \n \n \n \n \n \n \n \n \n
\n \n \n
    \n
  • \n Code your extension\n
  • \n
  • \n Run your extension with\n web-ext run\n or\n about: debugging)\n
  • \n
  • \n Test persistent and restart features\n
  • \n
  • \n Debug with the\n Addon Debugging Window\n
  • \n
\n
\n
    \n
  • \n Package your extension with\n web-ext build\n
  • \n
  • \n Create an\n addons.mozilla.org account\n
  • \n
  • \n Submit your extension\n
  • \n
  • \n Submit your source code\n (if required)\n
  • \n
  • \n Create an appealing listing\n
  • \n
\n
\n
    \n
  • Responded to Mozilla extension review
  • \n
  • Promote your extension
  • \n
  • \n Nominate your extension to be featured\n
  • \n
  • Update and improve your extension
  • \n
\n
\n
    \n
  • \n Retire your extension\n
  • \n
\n
\n\n\\* Or distribute your extension for [sideloading](https://extensionworkshop.com/documentation/publish/distribute-sideloading/), [desktop apps](https://extensionworkshop.com/documentation/publish/distribute-for-desktop-apps/), or [in an enterprise](https://extensionworkshop.com/documentation/enterprise/).\n\n**Have an extension you want to bring to Firefox?** We provide advice, guidelines, and tools to help making make porting straightforward. To get started, visit [Porting a Google Chrome extension](https://extensionworkshop.com/documentation/develop/porting-a-google-chrome-extension/).\n"},"__index_level_0__":{"kind":"number","value":0,"string":"0"}}},{"rowIdx":9061,"cells":{"repo_id":{"kind":"string","value":"data/mdn-content/files/en-us/mozilla/add-ons/webextensions"},"file_path":{"kind":"string","value":"data/mdn-content/files/en-us/mozilla/add-ons/webextensions/chrome_incompatibilities/index.md"},"content":{"kind":"string","value":"---\ntitle: Chrome incompatibilities\nslug: Mozilla/Add-ons/WebExtensions/Chrome_incompatibilities\npage-type: guide\n---\n\n{{AddonSidebar}}\n\nThe WebExtension APIs aim to provide compatibility across all the main browsers, so extensions should run on any browser with minimal changes.\n\nHowever, there are significant differences between Chrome (and Chromium-based browsers), Firefox, and Safari. In particular:\n\n- Support for WebExtension APIs differs across browsers. See [Browser support for JavaScript APIs](/en-US/docs/Mozilla/Add-ons/WebExtensions/Browser_support_for_JavaScript_APIs) for details.\n- Support for `manifest.json` keys differs across browsers. See the [\"Browser compatibility\" section](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json#browser_compatibility) on the [`manifest.json`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json) page for more details.\n- Extension API namespace:\n\n - **In Firefox and Safari:** Extension APIs are accessed under the `browser` namespace. The `chrome` namespace is also supported for compatibility with Chrome.\n - **In Chrome:** Extension APIs are accessed under the `chrome` namespace. (cf. [Chrome bug 798169](https://crbug.com/798169))\n\n- Asynchronous APIs:\n\n - **In Firefox and Safari:** Asynchronous APIs are implemented using promises.\n - **In Chrome:** In Manifest V2, asynchronous APIs are implemented using callbacks. In Manifest V3, support is provided for [promises](https://developer.chrome.com/docs/extensions/mv3/intro/mv3-overview/#promises) on most appropriate methods. (cf. [Chrome bug 328932](https://crbug.com/328932)) Callbacks are supported in Manifest V3 for backward compatibility.\n\nThe rest of this page details these and other incompatibilities.\n\n## JavaScript APIs\n\n### chrome.\\* and browser.\\* namespace\n\n- **In Firefox and Safari:** The APIs are accessed using the `browser` namespace.\n\n ```js\n browser.browserAction.setIcon({ path: \"path/to/icon.png\" });\n ```\n\n- **In Chrome:** The APIs are accessed using the `chrome` namespace.\n\n ```js\n chrome.browserAction.setIcon({ path: \"path/to/icon.png\" });\n ```\n\n### Callbacks and promises\n\n- **In Firefox and Safari (all versions), and Chrome (starting from Manifest Version 3):** Asynchronous APIs use [promises](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) to return values.\n\n ```js\n function logCookie(c) {\n console.log(c);\n }\n\n function logError(e) {\n console.error(e);\n }\n\n let setCookie = browser.cookies.set({\n url: \"https://developer.mozilla.org/\",\n });\n setCookie.then(logCookie, logError);\n ```\n\n- **In Chrome:** In Manifest V2, asynchronous APIs use callbacks to return values and {{WebExtAPIRef(\"runtime.lastError\")}} to communicate errors. In Manifest V3, callbacks are supported for backward compatibility, along with support for [promises](https://developer.chrome.com/docs/extensions/mv3/intro/mv3-overview/#promises) on most appropriate methods.\n\n ```js\n function logCookie(c) {\n if (chrome.runtime.lastError) {\n console.error(chrome.runtime.lastError);\n } else {\n console.log(c);\n }\n }\n\n chrome.cookies.set({ url: \"https://developer.mozilla.org/\" }, logCookie);\n ```\n\n### Firefox supports both the chrome and browser namespaces\n\nAs a porting aid, the Firefox implementation of WebExtensions supports `chrome` using callbacks and `browser` using promises. This means that many Chrome extensions work in Firefox without changes.\n\n> **Note:** The `browser` namespace is supported by Firefox and Safari. Chrome does not offer the `browser` namespace, until [Chrome bug 798169](https://crbug.com/798169) is resolved.\n\nIf you choose to write your extension to use `browser` and promises, Firefox provides a polyfill that should enable it to run in Chrome: .\n\n### Partially supported APIs\n\nThe [Browser support for JavaScript APIs](/en-US/docs/Mozilla/Add-ons/WebExtensions/Browser_support_for_JavaScript_APIs) page includes compatibility tables for all APIs that have any support in Firefox. Where there are caveats regarding support for an API method, property, type, or event, this is indicated in these tables with an asterisk \"\\*\". Selecting the asterisk expands the table to display a note explaining the caveat.\n\nThe tables are generated from compatibility data stored as [JSON files in GitHub](https://github.com/mdn/browser-compat-data).\n\nThe rest of this section describes the main compatibility issues you may need to consider when building a cross-browser extension. Also, remember to check the browser compatibility tables, as they may contain additional compatibility information.\n\n#### Notifications API\n\nFor `notifications.create()`, with `type \"basic\"`:\n\n- **In Firefox**: `iconUrl` is optional.\n- **In Chrome**: `iconUrl` is required.\n\nWhen the user clicks on a notification:\n\n- **In Firefox**: The notification is cleared immediately.\n- **In Chrome**: This is not the case.\n\nIf you call `notifications.create()` more than once in rapid succession:\n\n- **In Firefox**: The notifications may not display. Waiting to make subsequent calls within the `notifications.create()` callback function is not a sufficient delay to prevent this.\n\n#### Proxy API\n\nFirefox and Chrome include a Proxy API. However, the design of these two APIs is incompatible.\n\n- **In Firefox**: Proxies are set using the [proxy.settings](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/proxy/settings) property or [proxy.onRequest](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/proxy/onRequest) to provide [ProxyInfo](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/proxy/ProxyInfo) dynamically.\n See [proxy](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/proxy) for more information on the API.\n- **In Chrome**: Proxy settings are defined in a [`proxy.ProxyConfig`](https://developer.chrome.com/docs/extensions/reference/proxy/#type-ProxyConfig) object. Depending on Chrome's proxy settings, the settings may contain [`proxy.ProxyRules`](https://developer.chrome.com/docs/extensions/reference/proxy/#type-ProxyRules) or a [`proxy.PacScript`](https://developer.chrome.com/docs/extensions/reference/proxy/#type-PacScript). Proxies are set using the [proxy.settings](https://developer.chrome.com/docs/extensions/reference/proxy/#property-settings) property.\n See [chrome.proxy](https://developer.chrome.com/docs/extensions/reference/proxy/) for more information on the API.\n\n#### Tabs API\n\nWhen using `tabs.executeScript()` or `tabs.insertCSS()`:\n\n- **In Firefox**: Relative URLs passed are resolved relative to the current page URL.\n- **In Chrome**: Relative URLs are resolved relative to the extension's base URL.\n\nTo work cross-browser, you can specify the path as an absolute URL, starting at the extension's root, like this:\n\n```plain\n/path/to/script.js\n```\n\nWhen calling `tabs.remove()`:\n\n- **In Firefox**: The `tabs.remove()` promise is fulfilled after the `beforeunload` event.\n- **In Chrome**: The callback does not wait for `beforeunload`.\n\n#### WebRequest API\n\n- **In Firefox:**\n\n - Requests can be redirected only if their original URL uses the `http:` or `https:` scheme.\n - The `activeTab` permission does not allow for intercepting network requests in the current tab. (See [bug 1617479](https://bugzil.la/1617479))\n - Events are not fired for system requests (for example, extension upgrades or search bar suggestions).\n\n - **From Firefox 57 onwards:** Firefox makes an exception for extensions that need to intercept {{WebExtAPIRef(\"webRequest.onAuthRequired\")}} for proxy authorization. See the documentation for {{WebExtAPIRef(\"webRequest.onAuthRequired\")}}.\n\n - If an extension wants to redirect a public (e.g., HTTPS) URL to an [extension page](/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Extension_pages), the extension's `manifest.json` file must contain a [`web_accessible_resources`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/web_accessible_resources) key with the URL of the extension page.\n\n > **Note:** _Any_ website may link or redirect to that URL, and extensions should treat any input (POST data, for example) as if it came from an untrusted source, as a normal web page should.\n\n - Some of the `browser.webRequest.*` APIs allow for returning Promises that resolves `webRequest.BlockingResponse` asynchronously.\n\n- **In Chrome:** Only `webRequest.onAuthRequired` supports asynchronous `webRequest.BlockingResponse` by supplying `'asyncBlocking'`, through a callback instead of a Promise.\n\n#### Windows API\n\n- **In Firefox:** `onFocusChanged` of the {{WebExtAPIRef(\"windows\")}} API triggers multiple times for a focus change.\n\n### Unsupported APIs\n\n#### DeclarativeContent API\n\n- **In Firefox:** Chrome's [declarativeContent](https://developer.chrome.com/docs/extensions/reference/declarativeContent/) API [is not implemented](https://bugzil.la/1435864). In addition, Firefox [will not support](https://bugzil.la/1323433#c16) the `declarativeContent.RequestContentScript` API (which is rarely used and is unavailable in stable releases of Chrome).\n\n### Miscellaneous incompatibilities\n\n#### URLs in CSS\n\n- **In Firefox:** URLs in injected CSS files are resolved relative to _the CSS file_.\n- **In Chrome:** URLs in injected CSS files are resolved relative to _the page they are injected into_.\n\n#### Support for dialogs in background pages\n\n- **In Firefox:** [`alert()`](/en-US/docs/Web/API/Window/alert), [`confirm()`](/en-US/docs/Web/API/Window/confirm), and [`prompt()`](/en-US/docs/Web/API/Window/prompt) are not supported in background pages.\n\n#### web_accessible_resources\n\n- **In Firefox:** Resources are assigned a random {{Glossary(\"UUID\")}} that changes for every instance of Firefox: `moz-extension://«random-UUID»/«path»`. This randomness can prevent you from doing things, such as adding your extension's URL to another domain's CSP policy.\n- **In Chrome:** When a resource is listed in `web_accessible_resources`, it is accessible as `chrome-extension://«your-extension-id»/«path»`. The extension ID is fixed for an extension.\n\n#### Manifest \"key\" property\n\n- **In Firefox:** As Firefox uses random UUIDs for `web_accessible_resources`, this property is unsupported. Firefox extensions can fix their extension ID through the `browser_specific_settings.gecko.id` manifest key (see [browser_specific_settings.gecko](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/browser_specific_settings#firefox_gecko_properties)).\n- **In Chrome:** When working with an unpacked extension, the manifest may include a [`\"key\"` property](https://developer.chrome.com/docs/extensions/mv3/manifest/key/) to pin the extension ID across different machines. This is mainly useful when working with `web_accessible_resources`.\n\n#### Content script HTTP(S) requests\n\n- **In Firefox:** When a content script makes an HTTP(S) request, you _must_ provide absolute URLs.\n- **In Chrome:** When a content script makes a request (for example, using [`fetch()`](/en-US/docs/Web/API/Fetch_API/Using_Fetch)) to a relative URL (like `/api`), it is sent to `https://example.com/api`.\n\n#### Content script environment\n\n- **In Firefox:** The global scope of the [content script environment](/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_scripts#content_script_environment) is not strictly equal to `window` ([Firefox bug 1208775](https://bugzil.la/1208775)). More specifically, the global scope (`globalThis`) is composed of standard JavaScript features as usual, plus `window` as the prototype of the global scope. Most DOM APIs are inherited from the page through `window`, through [Xray vision](/en-US/docs/Mozilla/Add-ons/WebExtensions/Sharing_objects_with_page_scripts#xray_vision_in_firefox) to shield the content script from modifications by the web page. A content script may encounter JavaScript objects from its global scope or Xray-wrapped versions from the web page.\n- **In Chrome:** The global scope is `window`, and the available DOM APIs are generally independent of the web page (other than sharing the underlying DOM). Content scripts cannot directly access JavaScript objects from the web page.\n\n#### Executing code in a web page from content script\n\n- **In Firefox:** {{jsxref(\"Global_Objects/eval\", \"eval\")}} runs code in the context of the content script and `window.eval` runs code in the context of the page. See [Using `eval` in content scripts](/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_scripts#using_eval_in_content_scripts).\n- **In Chrome:** {{jsxref(\"Global_Objects/eval\", \"eval\")}} and `window.eval` always runs code in the context of the content script, not in the context of the page.\n\n#### Sharing variables between content scripts\n\n- **In Firefox:** You cannot share variables between content scripts by assigning them to `this.{variableName}` in one script and then attempting to access them using `window.{variableName}` in another. This is a limitation created by the sandbox environment in Firefox. This limitation may be removed; see [Firefox bug 1208775](https://bugzil.la/1208775).\n\n#### Content script lifecycle during navigation\n\n- **In Firefox:** Content scripts remain injected in a web page after the user has navigated away. However, window object properties are destroyed. For example, if a content script sets `window.prop1 = \"prop\"` and the user then navigates away and returns to the page `window.prop1` is undefined. This issue is tracked in [Firefox bug 1525400](https://bugzil.la/1525400).\n\n To mimic the behavior of Chrome, listen for the [pageshow](/en-US/docs/Web/API/Window/pageshow_event) and [pagehide](/en-US/docs/Web/API/Window/pagehide_event) events. Then simulate the injection or destruction of the content script.\n\n- **In Chrome:** Content scripts are destroyed when the user navigates away from a web page. If the user clicks the back button to return to the page through history, the content script is injected into the web page.\n\n#### \"per-tab\" zoom behavior\n\n- **In Firefox:** The zoom level persists across page loads and navigation within the tab.\n- **In Chrome:** Zoom changes are reset on navigation; navigating a tab always loads pages with their per-origin zoom factors.\n\nSee {{WebExtAPIRef(\"tabs.ZoomSettingsScope\")}}.\n\n## manifest.json keys\n\nThe main [`manifest.json`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json) page includes a table describing browser support for `manifest.json` keys. Where there are caveats around support for a given key, this is indicated in the table with an asterisk \"\\*\". Selecting the asterisk expands the table to display a note explaining the caveat.\n\nThe tables are generated from compatibility data stored as [JSON files in GitHub](https://github.com/mdn/browser-compat-data).\n\n## Native messaging\n\n### Connection-based messaging arguments\n\n**On Linux and Mac:** Chrome passes one argument to the native app, which is the origin of the extension that started it, in the form of `chrome-extension://«extensionID/»` (trailing slash required). This enables the app to identify the extension.\n\n**On Windows:** Chrome passes two arguments:\n\n1. The origin of the extension\n2. A handle to the Chrome native window that started the app\n\n### allowed_extensions\n\n- **In Firefox:** The manifest key is called `allowed_extensions`.\n- **In Chrome:** The manifest key is called `allowed_origins`.\n\n### App manifest location\n\n- **In Chrome:** The app manifest is expected in a different place. See [Native messaging host location](https://developer.chrome.com/docs/apps/nativeMessaging/#native-messaging-host-location) in the Chrome docs.\n\n### App persistence\n\n- **In Firefox:** When a native messaging connection is closed, Firefox kills the subprocesses if they do not break away. On Windows, the browser puts the native application's process into a [Job object]() and kills the job. Suppose the native application launches other processes and wants them to remain open after the native application is killed. In that case, the native application must use `CreateProcess`, instead of `ShellExecute`, to launch the additional process with the [`CREATE_BREAKAWAY_FROM_JOB`]() flag.\n\n## Data cloning algorithm\n\nSome extension APIs allow an extension to send data from one part of the extension to another, such as {{WebExtAPIRef(\"runtime.sendMessage()\")}}, {{WebExtAPIRef(\"tabs.sendMessage()\")}}, {{WebExtAPIRef(\"runtime.onMessage\")}}, the `postMessage()` method of {{WebExtAPIRef(\"runtime.port\")}}, and {{WebExtAPIRef(\"tabs.executeScript()\")}}.\n\n- **In Firefox:** The [Structured clone algorithm](/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm) is used.\n- **In Chrome:** The [JSON serialization algorithm](/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#description) is used. It may switch to structured cloning in the future ([issue 248548](https://crbug.com/248548)).\n\nThe Structured clone algorithm supports more types than the JSON serialization algorithm. A notable exception are (DOM) objects with a `toJSON` method. DOM objects are not cloneable nor JSON-serializable by default, but with a `toJSON()` method, these can be JSON-serialized (but still not cloned with the structured cloning algorithm). Examples of JSON-serializable objects that are not structured cloneable include instances of {{domxref(\"URL\")}} and {{domxref(\"PerformanceEntry\")}}.\n\nExtensions that rely on the `toJSON()` method of the JSON serialization algorithm can use {{jsxref(\"JSON.stringify()\")}} followed by {{jsxref(\"JSON.parse()\")}} to ensure that a message can be exchanged because a parsed JSON value is always structurally cloneable.\n"},"__index_level_0__":{"kind":"number","value":0,"string":"0"}}},{"rowIdx":9062,"cells":{"repo_id":{"kind":"string","value":"data/mdn-content/files/en-us/mozilla/add-ons/webextensions"},"file_path":{"kind":"string","value":"data/mdn-content/files/en-us/mozilla/add-ons/webextensions/your_second_webextension/index.md"},"content":{"kind":"string","value":"---\ntitle: Your second extension\nslug: Mozilla/Add-ons/WebExtensions/Your_second_WebExtension\npage-type: guide\n---\n\n{{AddonSidebar}}\n\nIf you've been through the [Your first extension](/en-US/docs/Mozilla/Add-ons/WebExtensions/Your_first_WebExtension) article, you've already got an idea of how to write an extension. In this article, you'll write a slightly more complex extension that demonstrates a few more of the APIs.\n\nThe extension adds a new button to the Firefox toolbar. When the user clicks the button, we display a popup enabling them to choose an animal. Once they choose an animal, we'll replace the current page's content with a picture of the chosen animal.\n\nTo implement this, we will:\n\n- **define a [browser action](/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Toolbar_button), which is a button attached to the Firefox toolbar**.\n For the button we'll supply:\n\n - an icon, called \"beasts-32.png\"\n - a popup to open when the button is pressed. The popup will include HTML, CSS, and JavaScript.\n\n- **define an icon for the extension**, called \"beasts-48.png\". This will be shown in the Add-ons Manager.\n- **write a content script, \"beastify.js\" that will be injected into web pages**.\n This is the code that will actually modify the pages.\n- **package some images of the animals, to replace images in the web page**.\n We'll make the images \"web accessible resources\" so the web page can refer to them.\n\nYou could visualize the overall structure of the extension like this:\n\n![The manifest.json file includes icons, browser actions, including popups, and web accessible resources. The choose beast JavaScript popup resource calls in the beastify script.](untitled-1.png)\n\nIt's a simple extension, but shows many of the basic concepts of the WebExtensions API:\n\n- adding a button to the toolbar\n- defining a popup panel using HTML, CSS, and JavaScript\n- injecting content scripts into web pages\n- communicating between content scripts and the rest of the extension\n- packaging resources with your extension that can be used by web pages\n\nYou can find [complete source code for the extension on GitHub](https://github.com/mdn/webextensions-examples/tree/main/beastify).\n\n## Writing the extension\n\nCreate a new directory and navigate to it:\n\n```bash\nmkdir beastify\ncd beastify\n```\n\n### manifest.json\n\nNow create a new file called \"manifest.json\", and give it the following contents:\n\n```json\n{\n \"manifest_version\": 2,\n \"name\": \"Beastify\",\n \"version\": \"1.0\",\n\n \"description\": \"Adds a browser action icon to the toolbar. Click the button to choose a beast. The active tab's body content is then replaced with a picture of the chosen beast. See https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Examples#beastify\",\n \"homepage_url\": \"https://github.com/mdn/webextensions-examples/tree/main/beastify\",\n \"icons\": {\n \"48\": \"icons/beasts-48.png\"\n },\n\n \"permissions\": [\"activeTab\"],\n\n \"browser_action\": {\n \"default_icon\": \"icons/beasts-32.png\",\n \"default_title\": \"Beastify\",\n \"default_popup\": \"popup/choose_beast.html\"\n },\n\n \"web_accessible_resources\": [\n \"beasts/frog.jpg\",\n \"beasts/turtle.jpg\",\n \"beasts/snake.jpg\"\n ]\n}\n```\n\n- The first three keys: [`manifest_version`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/manifest_version), [`name`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/name), and [`version`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/version), are mandatory and contain basic metadata for the extension.\n- [`description`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/description) and [`homepage_url`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/homepage_url) are optional, but recommended: they provide useful information about the extension.\n- [`icons`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/icons) is optional, but recommended: it allows you to specify an icon for the extension, that will be shown in the Add-ons Manager.\n- [`permissions`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions) lists permissions the extension needs. We're just asking for the [`activeTab` permission](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#activetab_permission) here.\n- [`browser_action`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/browser_action) specifies the toolbar button. We're supplying three pieces of information here:\n\n - `default_icon` is mandatory, and points to the icon for the button\n - `default_title` is optional, and will be shown in a tooltip\n - `default_popup` is used if you want a popup to be shown when the user clicks the button. We do, so we've included this key and made it point to an HTML file included with the extension.\n\n- [`web_accessible_resources`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/web_accessible_resources) lists files that we want to make accessible to web pages. Since the extension replaces the content in the page with images we've packaged with the extension, we need to make these images accessible to the page.\n\nNote that all paths given are relative to manifest.json itself.\n\n### The icon\n\nThe extension should have an icon. This will be shown next to the extension's listing in the Add-ons Manager (you can open this by visiting the URL \"about:addons\"). Our manifest.json promised that we would have an icon for the toolbar at \"icons/beasts-48.png\".\n\nCreate the \"icons\" directory and save an icon there named \"beasts-48.png\". You could use [the one from our example](https://raw.githubusercontent.com/mdn/webextensions-examples/main/beastify/icons/beasts-48.png), which is taken from the [Aha-Soft's Free Retina iconset](http://www.aha-soft.com/free-icons/free-retina-icon-set/), and used under the terms of its license.\n\nIf you choose to supply your own icon, It should be 48x48 pixels. You could also supply a 96x96 pixel icon, for high-resolution displays, and if you do this it will be specified as the `96` property of the `icons` object in manifest.json:\n\n```json\n\"icons\": {\n \"48\": \"icons/beasts-48.png\",\n \"96\": \"icons/beasts-96.png\"\n}\n```\n\n### The toolbar button\n\nThe toolbar button also needs an icon, and our manifest.json promised that we would have an icon for the toolbar at \"icons/beasts-32.png\".\n\nSave an icon named \"beasts-32.png\" in the \"icons\" directory. You could use [the one from our example](https://raw.githubusercontent.com/mdn/webextensions-examples/main/beastify/icons/beasts-32.png), which is taken from the [IconBeast Lite icon set](http://www.iconbeast.com/free/) and used under the terms of its [license](http://www.iconbeast.com/faq/).\n\nIf you don't supply a popup, then a click event is dispatched to your extension when the user clicks the button. If you do supply a popup, the click event is not dispatched, but instead, the popup is opened. We want a popup, so let's create that next.\n\n### The popup\n\nThe function of the popup is to enable the user to choose one of three beasts.\n\nCreate a new directory called \"popup\" under the extension root. This is where we'll keep the code for the popup. The popup will consist of three files:\n\n- **`choose_beast.html`** defines the content of the panel\n- **`choose_beast.css`** styles the content\n- **`choose_beast.js`** handles the user's choice by running a content script in the active tab\n\n```bash\nmkdir popup\ncd popup\ntouch choose_beast.html choose_beast.css choose_beast.js\n```\n\n#### choose_beast.html\n\nThe HTML file looks like this:\n\n```html\n\n\n \n \n \n \n\n \n
\n \n \n \n \n
\n
\n

Can't beastify this web page.

\n

Try a different page.

\n
\n \n \n\n```\n\nWe have a [`
`](/en-US/docs/Web/HTML/Element/div) element with an ID of `\"popup-content\"` that contains a button for each animal choice and a reset button. We have another `
` with an ID of `\"error-content\"` and a class `\"hidden\"`. We'll use that in case there's a problem initializing the popup.\n\nNote that we include the CSS and JS files from this file, just like a web page.\n\n#### choose_beast.css\n\nThe CSS fixes the size of the popup, ensures that the three choices fill the space, and gives them some basic styling. It also hides elements with `class=\"hidden\"`: this means that our `