Work with contextual identities

Many people need or want to interact with the web using multiple personas. They may have accounts for web-based work and personal email. They might sign out of their social media accounts before accessing online shopping, to ensure that any tracking scripts on the shopping sites can't pick up their social media activity. To address these requirements, users often end up working with a standard and private browser window or two different browsers.

To address this need, Firefox includes a feature known as contextual identities, container tabs or account containers. This feature enables the creation of a cookie container for each of the identities the user wants to use in their browser. Tabs can be associated with one of these identities, keeping cookies separate from those of other identities in the browser. The practical upshot of this is that, for example, a user could have a personal and work identity. They can then use the personal identity in one tab, where they sign into their personal web mail, and the work identity in another tab, where they sign into their work web mail.

For more background on this feature, see:

APIs for working with contextual identities

To use the contextual identity features in extensions, you’ll work with two APIs:

  • contextualIdentities which enable an extension to add, query, update, and delete contextual identities.
  • tabs or more specifically tabs.create which enables you to create a tab that uses a contextual identity’s container (cookies store).

权限

要使用 contextualIdentities API you need to include the "contextualIdentities" permission 在您的 manifest.json file. You don't need the "tabs" permission to use tabs.create however; you do need the "cookies" permission to specify the cookie container you want the tab to use.

Example walkthrough

The example extension contextual-identities provides a toolbar button with a popup that lists the identities in the browser. For each identity, the extension provides options to create a new tab using it’s cookies container or remove all of the identity’s tabs.

Here is a short video of the extension in action:

manifest.json

The main features of the manifest.json file are:

  • the permissions request:
      "permissions": [
          "contextualIdentities",
          "cookies"
      ],
    
    							
  • specification of the toolbar button (browseAction) that provides access to the extension’s features:
      "browser_action": {
        "browser_style": true,
        "default_title": "Contextual Identities",
        "default_popup": "context.html",
        "default_icon": {
          "128": "identity.svg"
        }
    
    							

context.html

A popup on the toolbar button provides the extension’s user interface. context.html implements this popup, but it’s just a shell into which the context.js script writes the list of contextual identities and their related options.

  <body>
    <div class="panel">
      <div id="identity-list"></div>
    </div>
  <script src="context.js"></script>
  </body>

					

context.js

All the features of the extension are implemented through context.js , which is invoked whenever the toolbar popup is displayed.

The script first gets the 'identity-list' div from context.html.

var div = document.getElementById('identity-list');

					

It then checks whether the contextual identities feature is turned on in the browser. If it's not on, information on how to activate it is added to the popup.

if (browser.contextualIdentities === undefined) {
  div.innerText = 'browser.contextualIdentities not available. Check that the privacy.userContext.enabled pref is set to true, and reload the add-on.';
} else {

					

Firefox installs with the contextual identity feature turned off, it’s turned on when an extension using the contextualIdentities API is installed. However, it's still possible for the user to turn the feature off, using an option on the preferences page (about:preferences), hence the need for the check.

The script now uses contextualIdentities.query to determine whether there are any contextual identities defined in the browser. If there are none, a message is added to the popup and the script stops.

  browser.contextualIdentities.query({})
    .then((identities) => {
      if (!identities.length) {
        div.innerText = 'No identities returned from the API.';
        return;
      }

					

If there are contextual identities present—Firefox comes with four default identities—the script loops through each one adding its name, styled in its chosen color, to the <div> element. The function createOptions() then adds the options to “create” or “close all” to the <div> before it’s added to the popup.

     for (let identity of identities) {
       let row = document.createElement('div');
       let span = document.createElement('span');
       span.className = 'identity';
       span.innerText = identity.name;
       span.style = `color: ${identity.color}`;
       console.log(identity);
       row.appendChild(span);
       createOptions(row, identity);
       div.appendChild(row);
     }
  });
}
function createOptions(node, identity) {
  for (let option of ['Create', 'Close All']) {
    let a = document.createElement('a');
    a.href = '#';
    a.innerText = option;
    a.dataset.action = option.toLowerCase().replace(' ', '-');
    a.dataset.identity = identity.cookieStoreId;
    a.addEventListener('click', eventHandler);
    node.appendChild(a);
  }
}

					

The script now waits for the user to select an option in the popup.

function eventHandler(event) {

					

If the user clicks the option to create a tab for an identity, one is opened using tabs.create by passing the identity’s cookie store ID.

  if (event.target.dataset.action == 'create') {
    browser.tabs.create({
      url: 'about:blank',
      cookieStoreId: event.target.dataset.identity
    });
  }

					

If the user selects the option to close all tabs for the identity, the script performs a tabs.query for all tabs that are using the identity’s cookie store. The script then passes this list of tabs to tabs.remove .

  if (event.target.dataset.action == 'close-all') {
    browser.tabs.query({
      cookieStoreId: event.target.dataset.identity
    }).then((tabs) => {
      browser.tabs.remove(tabs.map((i) => i.id));
    });
  }
  event.preventDefault();
}

					

了解更多

If you want to learn more about the contextualIdentities 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