Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.


See the Notes on Browser Extension Development column for a series of articles


Bookmarking means bookmarking a web site in a browser’s favorites so it can be accessed later. You can bookmark the current web page by clicking the star icon ⭐️ on the right of the browser address bar. Enter Chrome ://bookmarks/ in the address bar to open the bookmarks Manager. You can manage bookmarks in batches.

💡 If you are developing bookmarks-related extensions, you might also consider Override Pages to Override the bookmarks management page to provide a greater variety of functions.

In browsers, many bookmarks are stored and managed in a tree data structure. The basic unit of this data structure is the node BookmarkTreeNode, which has two types:

  • Bookmark, which is a leaf node, that is, a child node under which there is no subdivision
  • A folder, also known as a group, can contain child nodes under it

Chrome provides apis prefixed with Chrome.bookmarks, which are bookmarks-related methods.

💡 is required to declare bookmarks permissions in the configuration item permissions in the manifest manifest.json that appears in the extension when using the related API.

The BookmarkTreeNode object, which contains the following common attributes, is returned by these methods:

  • childrenArray (optional, not available if the node is a bookmark), an array containing children
  • dateAddedValue (optional), the time when a node is created, in millisecondsnew Date(dateAdded)Get the JS Date object
  • dateGroupModifiedValue (Optional). If the node is a folder, this value indicates the last time when the contents of the folder were modified
  • idString, which is the unique identifier of a node, unique for each node in the browser bookmark “tree”
  • indexValue (optional), the sort of the node in its parent folder, indexed from0start
  • parentIdString (Optional, not available when node is root folder)
  • urlString (Optional, this property is available when the node is a bookmark, clicking the bookmark will navigate to the specified web page address)

Open the bookmarks

Chrome.bookmarks.get (idOrIdList: String | string []) for specific bookmarks node, or multiple bookmarks node array, it is an asynchronous function that returns immediately is a Promise, eventually returns the corresponding node BookmarkTreeNode bookmarks (or array).

// Encapsulate a bookmark opening method with Chrome's API
// This method takes three arguments
// * The first argument is the ID of the bookmark node that you want to open
// * The second parameter is the open mode, which can be new or current, which means to open a bookmark in a new TAB, or to open a bookmark in the current TAB
// * The third parameter is whether to set the new TAB to the active TAB
const openBookmark = (nodeId, mode = 'new', active = true) = > new Promise((resolve, reject) = > {
    // Get bookmarks by node ID
    chrome.bookmarks.get(nodeId)
    .then(async (nodes) => {
      const { url } = nodes[0];
      // Determine which TAB to open the bookmark on according to the parameters
      let tab;
      if (mode === 'new') {
        // open on new tab
        tab = await createNewTab(active);
      } else if (mode === 'current') {
        // open on current active tab
        tab = await getActiveTab();
      }
      // Open the bookmark by updating the attribute URL of the TAB page
      await chrome.tabs.update(tab.id, {
        url,
      });
      resolve(tab);
    });
});

const createNewTab = async (active = true) = > {const newTab = await chrome.tabs.create({
    active,
  });
  return newTab;
};

const getActiveTab = async() = > {CurrentWindow the active TAB of the currentWindow
  // Since this method returns an array with only one active TAB, we can use deconstruction to get a unique element of the array
  const [tab] = await chrome.tabs.query({
    active: true.currentWindow: true});return tab;
};
Copy the code

Create a bookmark

Chrome. Bookmarks. Create (Bookmark: CreateDetails creates a bookmark node, which can be a bookmark or a folder (if the input configuration object omits the property URL or if the property value is NULL). This is an asynchronous function that immediately returns a Promise, The BookmarkTreeNode is returned.

This method takes as an input a configuration object with the following common properties:

  • indexValue (optional) that specifies the order of the new bookmark node in its parent
  • parentIdA string (optional) specifying under which parent the new bookmark is to be added. The default is 📁Other bookmarksOther bookmarksFolder as parent node
  • titleString (optional) the name of the bookmark node
  • urlString (optional), the url of the bookmark node (omit this property if the new node is a folder)

Since bookmarks are stored and managed in a tree data structure, when creating a bookmark node, you need to pass a configuration object to the above method, specifying which parent node the new bookmark node is under

// Under the folder bookmarkBar, add a bookmark node named New Folder, which is a folder
chrome.bookmarks.create({
  'parentId': bookmarkBar.id,
  'title': 'new folder'
}).then(folder= > {  
  console.log("added folder: " + newFolder.title);
})

// Add a bookmark named Google
chrome.bookmarks.create({
  'parentId': FolderId,
  'title': 'Google'.'url': 'https://www.google.com.hk/'});Copy the code