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.

Permissions

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

"permissions": [
"bookmarks"
],

Features

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.

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.

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:

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 HTMLHyperlinkElementUtils by adding the tab’s URL to an <a> element and then getting the protocol using the protocol property.

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.