Work with the Cookies API

With the Cookies API your extensions have access to capabilities similar to those used by websites to store and read cookies. The API’s features give extensions the ability to store information on a site-by-site basis. So, as we shall see in the example, you could store details of a user’s choice of background color for a site. Then, when the user revisits the site, your extension can use the API’s ability to get details about cookies and read them to recover the user’s choice and apply it to the website.

注意: The behavior of cookies can be controlled using the privacy.websites cookieConfig property. This property controls whether and how cookies are accepted or whether all cookies are treated as session cookies.

权限

To use the Cookies API you need to request both the "cookies" permission and host permissions for the protocols, domains, or websites you want to access or use "<all_urls>" to access any protocol and domain. The way in which you define your host permission string affects your extension’s ability to read, write, and delete cookies.

Host permission string

读取

Write/Delete

Secure Non-secure Secure Non-secure
"http://*.example.com/" No Main and sub domains, with any path Main and sub domains, with any path Main and sub domains, with any path
"https://www.example.com/" www.example.com or .example.com with any path, but no subdomains www.example.com or .example.com with any path, but no subdomains www.example.com or .example.com with any path, but no subdomains www.example.com or .example.com with any path, but no subdomains
"*://*.example.com/" Main and sub domains, with any path Main and sub domains, with any path Main and sub domains, with any path Main and sub domains, with any path
"<all_urls>" Any domain with any path Any domain with any path Any domain with any path Any domain with any path

Firefox provides three types of cookie store:

  • The default store, which stores cookies from normal browsing.
  • Private browsing mode stores, which stores cookies created during a private browsing session. These stores and any cookies they contain are removed when the related private browsing window closes.
  • Container tabs stores, which stores cookies for each contextual identity in Firefox. Contextual identities enable a user to maintain multiple identities within one browser window. This is useful if, for example, you’ve a company and personal email account on Gmail. With contextual identities, you can open one tab against a personal identity and a second tab against a business identity. Each tab can then sign into Google mail with a different username, and the two accounts can be used side-by-side. For more information, see Security/Contextual Identity Project/Containers in the Mozilla wiki.

You can find out what cookie stores are available using cookies.getAllCookieStores , which returns an object containing the ID of each cookie store and a list of the IDs of the tabs using each cookie store.

Example walkthrough

The example extension cookie-bg-picker allows its user to pick a color and icon that are applied to the background of a site’s web pages. These choices are saved on a per-site basis using cookies.set . When a page from the site is opened, cookies.get reads any earlier choice, and the extension applies it to the web page. A reset option removes the background icon and color from the site as well as the cookie, using cookies.remove . It also uses cookies.onChanged to listen for changes to cookies, sending details of the change to the console.

This video shows the extension in action:

This example also uses the Tabs and Runtime APIs, but we’ll discuss those features only in passing.

manifest.json

The key feature of the manifest.json file relating to the use of the Cookies API is the permissions request:

  "permissions": [
      "tabs",
      "cookies",
      "<all_urls>"
],

								

Here, the extension requests permission to use the Cookies API ( "cookies" ) with all websites ( "<all_urls>" ). This enables the extension to save the background color icon choice for any website.

Scripts—bgpicker.js

The extension’s UI uses a toolbar button ( browserAction ) implemented with bgpicker.html that calls bgpicker.js . Together these allow the user to select the icon and enter the color they want to apply as the site background. They also provide the option to clear those settings.

bgpicker.js handles the selection of icon or entry of a color for the background in separate functions.

To handle the icon buttons the script first gathers all the class names used for the buttons in the HTML file:

var bgBtns = document.querySelectorAll('.bg-container button');

								

It then loops through all the buttons assigning them their image and creating an onclick listener for each button:

for(var i = 0; i < bgBtns.length; i++) {
  var imgName = bgBtns[i].getAttribute('class');
  var bgImg = 'url(\'images/' + imgName + '.png\')';
  bgBtns[i].style.backgroundImage = bgImg;
  bgBtns[i].onclick = function(e) {

								

When a button is clicked, its corresponding listener function gets the button class name and then the icon path which it passes to the page’s content script ( updatebg.js ) using a message. The content script then applies the icon to the web page’s background. Meanwhile, bgpicker.js stores the details of the icon applied to the background in a cookie:

    cookieVal.image = fullURL;
    browser.cookies.set({
    url: tabs[0].url,
    name: "bgpicker",
    value: JSON.stringify(cookieVal)
  })

								

The color setting is handled in a similar way, triggered by a listener on the color input field. When a color is entered the active tab is discovered and the color selection details sent, using a message, to the page’s content script to be applied to the web page background. Then the color selection is added to the cookie:

    cookieVal.color = currColor;
    browser.cookies.set({
    url: tabs[0].url,
    name: "bgpicker",
    value: JSON.stringify(cookieVal)

								

When the user clicks the reset button, which has been assigned to the variable reset:

var reset = document.querySelector('.color-reset button');

								

reset.onclick first finds the active tab. Then, using the tab’s ID it passes a message to the page’s content script ( updatebg.js ) to get it to remove the icon and color from the page. The function then clears the cookie values (so the old values aren’t carried forward and written onto a cookie created for a new icon or color selection on the same page) before removing the cookie:

    cookieVal = { image : '',
                  color : '' };
    browser.cookies.remove({
    url: tabs[0].url,
    name: "bgpicker"

								

Also, so you can see what is going on with the cookies, the script reports on all changes to cookies in the console:

browser.cookies.onChanged.addListener((changeInfo) => {
  console.log(`Cookie changed:\n
    * Cookie: ${JSON.stringify(changeInfo.cookie)}\n
    * Cause: ${changeInfo.cause}\n
    * Removed: ${changeInfo.removed}`);
  });

								

Scripts—background.js

A background script ( background.js ) provides for the possibility that the user has chosen a background icon and color for the website in an earlier session. The script listens for changes in the active tab, either the user switching between tabs or changing the URL of the page displayed in the tab. When either of these events happen, cookieUpdate() is called.   cookieUpdate() in turn uses getActiveTab() to get the active tab ID. The function can then check whether a cookie for the extension exists, using the tab’s URL:

    var gettingCookies = browser.cookies.get({
      url: tabs[0].url,
      name: "bgpicker"
    });

								

"bgpicker" cookie exists for the website, the details of the icon and color selected earlier are retrieved and passed to the  content script updatebg.js using messages:

    gettingCookies.then((cookie) => {
      if (cookie) {
        var cookieVal = JSON.parse(cookie.value);
        browser.tabs.sendMessage(tabs[0].id, {image: cookieVal.image});
        browser.tabs.sendMessage(tabs[0].id, {color: cookieVal.color});
      }
    });

								

Other features

In addition to the APIs mentioned so far, the Cookies API also offers cookies.getAll . This function takes the details object to specify filters for the selected cookies and returns an array of cookies.Cookie objects that match the filter criteria.

了解更多

If you want to learn more about the Cookies API, check out:

Found a problem with this page?

最后修改: , 由 MDN 贡献者

  1. 浏览器扩展名
  2. 快速入门
    1. What are extensions?
    2. Your first extension
    3. Your second extension
    4. Anatomy of an extension
    5. Example extensions
    6. What next?
  3. 概念
    1. Using the JavaScript APIs
    2. Content scripts
    3. Match patterns
    4. Working with files
    5. 国际化
    6. Content Security Policy
    7. Native messaging
    8. Differences between API implementations
    9. Chrome incompatibilities
  4. 用户界面
    1. 用户界面
    2. Toolbar button
    3. Address bar button
    4. Sidebars
    5. Context menu items
    6. Options page
    7. Extension pages
    8. Notifications
    9. Address bar suggestions
    10. Developer tools panels
  5. 如何
    1. Intercept HTTP requests
    2. Modify a web page
    3. Insert external content
    4. Share objects with page scripts
    5. Add a button to the toolbar
    6. Implement a settings page
    7. Work with the Tabs API
    8. Work with the Bookmarks API
    9. Work with the Cookies API
    10. Work with contextual identities
    11. Interact with the clipboard
    12. Build a cross-browser extension
  6. Firefox differentiators
  7. JavaScript API
    1. Browser support for JavaScript APIs
    2. alarms
    3. bookmarks
    4. browserAction
    5. browserSettings
    6. browsingData
    7. captivePortal
    8. clipboard
    9. 命令
    10. contentScripts
    11. contextualIdentities
    12. Cookie
    13. devtools
    14. dns
    15. downloads
    16. events
    17. extension
    18. extensionTypes
    19. find
    20. history
    21. i18n
    22. identity
    23. idle
    24. management
    25. menus
    26. notifications
    27. omnibox
    28. pageAction
    29. permissions
    30. pkcs11
    31. privacy
    32. proxy
    33. runtime
    34. search
    35. sessions
    36. sidebarAction
    37. storage
    38. tabs
    39. theme
    40. topSites
    41. 类型
    42. userScripts
    43. webNavigation
    44. webRequest
    45. windows
  8. Manifest keys
    1. 介绍
    1. 作者
    2. background
    3. browser_action
    4. browser_specific_settings
    5. chrome_settings_overrides
    6. chrome_url_overrides
    7. 命令
    8. content_scripts
    9. content_security_policy
    10. default_locale
    11. description
    12. developer
    13. devtools_page
    14. dictionaries
    15. externally_connectable
    16. homepage_url
    17. icons
    18. incognito
    19. manifest_version
    20. name
    21. offline_enabled
    22. omnibox
    23. optional_permissions
    24. options_page
    25. options_ui
    26. page_action
    27. permissions
    28. protocol_handlers
    29. short_name
    30. sidebar_action
    31. storage
    32. theme
    33. theme_experiment
    34. user_scripts
    35. version
    36. version_name
    37. web_accessible_resources
  9. Extension Workshop
    1. Develop
    2. Publish
    3. Manage
    4. Enterprise
  10. Contact us
  11. Channels
    1. Add-ons blog
    2. Add-ons forum
    3. Add-ons chat