Work with the Bookmarks API

Bookmarks enable users to collect and organize lists of web pages, so they can easily get back to their favorites. Using the Bookmarks API, your extensions can manipulate bookmarks in much the same way users can.

权限

To make use of the Bookmarks API, you need to ask for the "bookmarks" permission in your extension’s manifest.json file:

"permissions": [
  "bookmarks"
],

					

特征

The Bookmarks API lets your extension do the things users can do with bookmarks and includes functions for:

Example walkthrough

To gain an understanding of how to work with the Bookmarks API let’s take a look at the bookmark-it example. This example adds a toolbar icon ( browserAction ) which, when clicked, adds or removes the current page from bookmarks. If the page is bookmarked (or removed from bookmarks) in some other way, the icon is updated to show the state of the page’s bookmarking.

This video shows the extension in action:

manifest.json

manifest.json describes the extension:

{
  "manifest_version": 2,
  "name": "Bookmark it!",
  "version": "1.1",
  "description": "A simple bookmark button",
  "homepage_url": "https://github.com/mdn/webextensions-examples/tree/master/bookmark-it",

					

Defines the icons that’ll be used to represent the extension, in places such as the add-on manager.

  "icons": {
    "48": "icons/bookmark-it.png",
    "96": "icons/bookmark-it@2x.png"
  },

					

Requests permissions. "bookmarks" is requested to enable use of the Bookmarks API. "tabs" is requested so that the active tab’s URL and title can be read and used to create or find the page’s bookmark. The need for the Tabs API to access these details means that you’re unlikely to use the Bookmark API without the Tabs API.

  "permissions": [
    "bookmarks",
    "tabs"
  ],

					

Sets up the basic toolbar button details. Most of the button’s features will be set up in code after the page’s bookmark status is known.

  "browser_action": {
    "default_icon": "icons/star-empty-38.png",
    "default_title": "Bookmark it!"
  },

					

Defines the background script that’ll add and remove the page’s bookmark and set the characteristics of the toolbar button.

  "background": {
    "scripts": ["background.js"]
  }
}

					

background.js

As with any background script, background.js is run as soon as the extension is started. Initially the script calls updateActiveTab() that starts by obtaining the Tabs object for the current tab, using tabs.query , and passing the object to updatetab() with this code:

  var gettingActiveTab = browser.tabs.query({active: true, currentWindow: true});
  gettingActiveTab.then(updateTab);

					

updatetab() first passes the active tab’s URL to isSupportedProtocol() :

  function updateTab(tabs) {
    if (tabs[0]) {
      currentTab = tabs[0];
      if (isSupportedProtocol(currentTab.url)) {

					

isSupportedProtocol() determines if the URL displayed in the active tab is one that can be bookmarked. To extract the protocol from the tab’s URL, the extension takes advantage of the HTMLAnchorElement by adding the tab’s URL to an <a> element and then getting the protocol using the 协议 特性。

  function isSupportedProtocol(urlString) {
    var supportedProtocols = ["https:", "http:", "file:"];
    var url = document.createElement('a');
    url.href = urlString;
    return supportedProtocols.indexOf(url.protocol) != -1;
  }

					

If the protocol is one supported by bookmarks, the extension determines if the tab’s URL is already bookmarked and if it is, calls updateIcon() :

      var searching = browser.bookmarks.search({url: currentTab.url});
      searching.then((bookmarks) => {
        currentBookmark = bookmarks[0];
        updateIcon();

					

updateIcon() sets the toolbar button’s icon and title, depending on whether the URL is bookmarked or not.

function updateIcon() {
  browser.browserAction.setIcon({
    path: currentBookmark ? {
      19: "icons/star-filled-19.png",
      38: "icons/star-filled-38.png"
    } : {
      19: "icons/star-empty-19.png",
      38: "icons/star-empty-38.png"
    },
    tabId: currentTab.id
  });
  browser.browserAction.setTitle({
    // Screen readers can see the title
    title: currentBookmark ? 'Unbookmark it!' : 'Bookmark it!',
    tabId: currentTab.id
  });
}

					

With the toolbar button initialized, the extension starts listening for a click on the toolbar button, calling toggleBookmark() when that happens.

browser.browserAction.onClicked.addListener(toggleBookmark);

					

toggleBookmark() uses the result from the search made by updateTabs() , which looks for the presence of the URL in a bookmark, to determine whether to remove or add a bookmark for the current URL.

function toggleBookmark() {
  if (currentBookmark) {
    browser.bookmarks.remove(currentBookmark.id);
  } else {
    browser.bookmarks.create({title: currentTab.title, url: currentTab.url});
  }
}

					

To update the toolbar icon, the extension listens for the creation or removal of bookmarks. This approach has the benefit of capturing both the bookmark update made by the extension and any update made by the user outside the extension.

// listen for bookmarks being created
browser.bookmarks.onCreated.addListener(updateActiveTab);
// listen for bookmarks being removed
browser.bookmarks.onRemoved.addListener(updateActiveTab);

					

Finally, the extension listens for a change to the active tab’s URL, or the user switching to another tab or window. These actions could change the viewed URL and therefore the status of the extension’s toolbar icon.

// listen to tab URL changes
browser.tabs.onUpdated.addListener(updateActiveTab);
// listen to tab switching
browser.tabs.onActivated.addListener(updateActiveTab);
// listen for window switching
browser.windows.onFocusChanged.addListener(updateActiveTab);

					

了解更多

If you want to learn more, check out the Bookmarks API reference .

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