Exemplos de Extensões

Para ajudar a ilustrar como desenvolver extensões, nós mantemos um repositório com simples exemplos de extensões em https://github.com/mdn/webextensions-examples. Este artigo descreve a WebExtension APIs utilizadas neste respositório.Estes exemplos funcionam no Firefox Nightly: A maioria funciona em versões anteriores do Firefox, porém verifique a chave strict_min_version no manifest.json da extensão por certificação.Se você quiser experimentar estes exemplos, você tem três opções principais:

  1. Clonar o repositório, então carregue a extensão diretamente de seu diretório de origem, usando o recurso "Load Temporary Add-on". A extensão permanecerá carregada até você reiniciar o Firefox.
  2. Clonar o repositório, então use a ferramenta linha de comando web-ext para executar o Firefox com a extensão instalada.
  3. Clonar o repositório, então vá até o diretório de build (construção). Isto contém as versões construídas e assinadas de todos os exemplos, então você pode simplesmente abrir eles no Firefox (usando Arquivo/Abrir arquivo) e instalar eles permanentemente, como uma extensão que você pode instalar de addons.mozilla.org.

Se você quer contribuir com o respositório, nos envie um pull request.

NameDescriptionJavaScript APIs
annotate-pageDisplays a sidebar that lets you take notes on web pages.storage.local
tabs.onActivated
tabs.onUpdated
tabs.query()
tabs.Tab
windows.getCurrent()
windows.Window
apply-cssAdds a page action to the toolbar. Click the button to apply a red border using injected CSS. Click the button again to remove the CSS.pageAction.getTitle()
pageAction.onClicked
pageAction.setIcon()
pageAction.setTitle()
pageAction.show()
tabs.insertCSS()
tabs.onUpdated
tabs.query()
tabs.removeCSS()
tabs.Tab
beastifyAdds 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.extension.getURL()
runtime.onMessage
tabs.executeScript()
tabs.insertCSS()
tabs.query()
tabs.removeCSS()
tabs.sendMessage()
tabs.Tab
bookmark-itAdds a bookmark button to the toolbar. Click the button to toggle a bookmark for the current page.bookmarks.create()
bookmarks.onCreated
bookmarks.onRemoved
bookmarks.remove()
bookmarks.search()
browserAction.onClicked
browserAction.setIcon()
browserAction.setTitle()
tabs.onActivated
tabs.onUpdated
tabs.query()
tabs.Tab
windows.onFocusChanged
borderifyAdds a solid red border to all webpages matching mozilla.org.
chill-outShow a page action after a period of inactivity. Show cat gifs when the page action is clicked.alarms.clearAll()
alarms.create()
alarms.onAlarm
pageAction.hide()
pageAction.onClicked
pageAction.show()
tabs.get()
tabs.onActivated
tabs.onUpdated
tabs.query()
tabs.update()
commandsDemonstrates using the commands API to set up a keyboard shortcut. The shortcut created is accessed using Ctrl+Shift+U (Command+Shift+U on a Mac).getAll()
onCommand
commands.reset()
commands.update()
tabs.create()
content-script-registerIllustrates how an extension can register URL-matching content scripts at runtime.contentScripts.register()
runtime.onMessage
runtime.sendMessage()
context-menu-copy-link-with-typesAdd a context menu option to links to copy the link to the clipboard, as plain text and as a link in rich HTML.create
onClicked
tabs.executeScript()
contextual-identitiesList, create, and remove contextual identities.contextualIdentities.query()
tabs.create()
tabs.query()
tabs.remove()
cookie-bg-pickerAllows the user to customize the background color and tiled pattern on sites they visit, and also saves their preferences via a cookie, reapplying them whenever they revisit a site they previously customized.cookies.get()
cookies.onChanged
cookies.remove()
cookies.set()
extension.getURL()
runtime.onMessage
tabs.onActivated
tabs.onUpdated
tabs.query()
tabs.Tab
tabs.sendMessage()
devtools-panelsDemonstrates some of the devtools APIs.devtools.inspectedWindow
devtools.panels
runtime.getURL()
runtime.onMessage
runtime.sendMessage()
tabs.executeScript()
discogs-searchDemonstrates adding a custom search engine with the chrome_settings_overrides key.
dnr-block-onlyDemonstrates how to block network requests without host permissions using the declarativeNetRequest API with the `declarative_net_request` manifest key.declarativeNetRequest.Rule
declarativeNetRequest.RuleAction
declarativeNetRequest.RuleCondition
dnr-dynamic-with-optionsDemonstrates a generic way to request host permissions and register declarativeNetRequest rules to modify network requests, without any install-time permission warnings. The options_ui page offers a way to request permissions and register DNR rules.declarativeNetRequest.Rule
declarativeNetRequest.getDynamicRules
declarativeNetRequest.getSessionRules
declarativeNetRequest.updateDynamicRules
declarativeNetRequest.updateSessionRules
permissions.getAll()
permissions.remove()
permissions.request()
dnr-redirect-urlDemonstrates multiple ways to redirect requests using the declarativeNetRequest API through the `declarative_net_request` manifest key. Demonstrates aspects of Manifest Version 3 (MV3): action, host_permissions, and web_accessible_resources, and includes a comparison with Manifest Version 2 (MV2).declarativeNetRequest.Redirect
declarativeNetRequest.Rule
declarativeNetRequest.RuleAction
declarativeNetRequest.RuleCondition
declarativeNetRequest.URLTransform
permissions.contains()
permissions.remove()
permissions.request()
dynamic-themeDynamic theme examplealarms.create()
alarms.onAlarm
theme.update()
emoji-substitutionReplaces words with emojis.
eslint-exampleDemonstrates how to configure an extension with eslint.
export-helpersDemonstrates how to use export helpers like cloneInto to share objects with page scripts.notifications.create()
runtime.onMessage
runtime.sendMessage()
favourite-colourAn example options page, letting you store your favourite colour.browserAction.onClicked
runtime.openOptionsPage()
storage.managed
storage.sync
find-across-tabsDemonstration of the find API.browserAction.onClicked
extension.getBackgroundPage()
find.find()
find.highlightResults()
runtime.getURL()
runtime.onMessage
runtime.sendMessage()
tabs.create()
tabs.query()
tabs.Tab
firefox-code-searchDemonstrates how to use the omnibox API.omnibox.onInputChanged
omnibox.onInputEntered
omnibox.setDefaultSuggestion()
tabs.create()
tabs.update()
forget-itDemonstrates how to use the browsingData API.browserAction.onClicked
browsingData.remove()
notifications.create()
storage.local
google-userinfoDemonstrates how to use the identity API.browserAction.onClicked
identity.getRedirectURL()
identity.launchWebAuthFlow
notifications.create()
history-deleterHistory API demo: deletes history items for a given domainhistory.deleteUrl()
history.search()
pageAction.show()
tabs.onUpdated
tabs.query()
http-responseDemonstrates how to rewrite HTTP responses using the webRequest.filterResponseData() API.webRequest.filterResponseData()
webRequest.onBeforeRequest
imagifyUsing a sidebar, illustrates the use of file picker and drag and drop. A content script replaces the current page content with the chosen image.extension.getURL()
runtime.onMessage
tabs.executeScript()
tabs.query()
tabs.sendMessage()
latest-downloadShows the last downloaded item, and lets you open or delete it.downloads.erase()
downloads.getFileIcon()
downloads.open()
downloads.removeFile()
downloads.search()
list-cookiesThis extensions list the cookies in the active tab.cookies.getAll()
tabs.query()
menu-accesskey-visibleShows how to set up a single letter access key for a menu item.i18n.getMessage()
menus.update()
menus.create()
menus.onClicked
menu-demoDemonstrates adding and manipulating menu items using the menus API.i18n.getMessage()
menus.create()
menus.onClicked
menus.remove()
menus.update()
runtime.lastError
tabs.executeScript()
menu-labelled-openShows how an extension can listen for the display of a menu and then add, remove, or update its menu items.menus.create()
menus.onClicked
menus.onShown
menus.refresh()
menus.update()
tabs.update()
menu-remove-elementShows how to detect the page element at the cursor position and remove that element, or a parent element, from the page. This example includes use of the polyfill, illustrating cross-browser extension development.menus.create()
menus.onClicked
menus.getTargetElement()
pageAction.openPopup()
pageAction.show()
tabs.executeScript()
menu-searchIllustrates how to retrieve a list of search engines and issue a search request, using search engine details added to the context menu for selected text.search.search()
search.get()
menus.create()
menus.onClicked
mocha-client-testsThis example shows two methods of testing an extension: running tests from within the extension, and running tests from the command line using Karma.runtime.onMessage
runtime.sendMessage()
native-messagingExample of native messaging, including a Python application and an extension which exchanges messages with it.browserAction.onClicked
runtime.connectNative()
navigation-statsDemonstration of the webNavigation API, showing basic stats about which pages you've visited.storage.local
webNavigation.onCommitted
webNavigation.onCompleted
notify-link-clicks-i18nShows a localized notification when the user clicks on links.extension.getURL()
i18n.getMessage()
notifications.create()
runtime.onMessage
runtime.sendMessage()
open-my-page-buttonAdds a browser action icon to the toolbar. When the browser action is clicked, the add-on opens a page that was packaged with it.browserAction.onClicked
tabs.create()
page-to-extension-messagingDemonstrates how a web page and a content script can exchange messages. Visit https://mdn.github.io/webextensions-examples/content-script-page-script-messaging.html for the demo.
permissionsDemonstrates optional permissions using the permissions API.browserAction.onClicked
permissions.getAll()
permissions.remove()
permissions.request()
runtime.getURL()
tabs.create()
private-browsing-themeExample dynamic theme: sets a dark theme for private windows.theme.reset()
theme.update()
windows.getAll()
windows.onCreated
proxy-blockerUses the proxy API to block requests to hosts specified on a list.extension.getURL()
proxy.onRequest
proxy.onError
storage.local
storage.onChanged
quicknoteAllows the user to make quick notes by clicking a button and entering text into the resulting popup. The notes are saved in storage.storage.local
root-cert-statsShows how to get details about a request's TLS connection.webRequest.getSecurityInfo()
runtime-examplesDemo of various runtime APIs.browserAction.onClicked
notifications.create()
runtime.getManifest()
runtime.onInstalled
runtime.reload()
selection-to-clipboardDemonstrates how to write to the clipboard from a content script
session-stateDemonstrates how to retrieve extension-defined state from restored tabs.menus.create()
menus.onClicked
sessions.getTabValue()
sessions.setTabValue()
tabs.insertCSS()
tabs.onCreated
tabs.onUpdated
tabs.query()
store-collected-imagesDemonstrates how to use the idb-file-storage library to store and manipulate files in an extension.browserAction.onClicked
create
onClicked
runtime.onMessage
runtime.sendMessage()
tabs.create()
windows.create()
stored-credentialsPerforms basic authentication by supplying stored credentials.storage.local
webRequest.onAuthRequired
webRequest.onCompleted
webRequest.onErrorOccurred
tabs-tabs-tabsDemonstrates tab manipulation: opening, closing, moving, zooming tabs.browserAction.setBadgeBackgroundColor()
browserAction.setBadgeText()
tabs.create()
tabs.duplicate()
tabs.getZoom()
tabs.move()
tabs.onCreated
tabs.onMoved
tabs.onRemoved
tabs.query()
tabs.reload()
tabs.remove()
tabs.setZoom()
tabs.Tab
tabs.update()
theme-integrated-sidebarA sidebar that integrates with the current theme.theme.getCurrent()
theme.onUpdated
windows.getCurrent()
theme-switcherAn example of how to use the management API for themes.management.getAll()
management.setEnabled()
themesA collection of themes illustrating:
  • weta_fade: a basic theme employing a single image specified in theme_frame:.
  • weta_fade_chrome: the weta_fade theme implemented with Chrome compatible manifest keys.
  • weta_tiled: a theme using a tiled image.
  • weta_mirror: a theme using multiple images and aligning those images in the header.
  • animated: use of an animated PNG.
top-sitesDemonstration of the topSites API.topSites.get()
user-agent-rewriterDemonstrates using the webRequest API to rewrite the User-Agent HTTP header.extension.getBackgroundPage()
webRequest.onBeforeSendHeaders
user-script-registerIllustrates how an extension can register URL-matching user scripts at runtime.userScripts.register()
runtime.onMessage
runtime.sendMessage()
webpack-modulesDemonstrates how to use webpack to package npm modules in an extension.runtime.onMessage
runtime.sendMessage()
window-manipulatorDemonstrates how to manipulate windows: opening, closing, resizing windows.windows.create()
windows.getAll()
windows.getCurrent()
windows.remove()
windows.update()
windows.Window
open-irc-linksDemonstrates the use of protocol handlers.