Add a context menu option to bookmark a link

I would like to add a context menu option “Bookmark This Link Now” which will be like “Bookmark This Link” but will skip the dialog box, which I always just hit “Save” on anyway. The following works except that I don’t know how to set the title of the link. “Bookmark This Link” seems to create the title from the text of the link, i.e., the text between the <a> and </a>. How can I read this text? In the code below the url is sent in the info object, but the text is not. This is what I have so far:

browser.contextMenus.create({
  id:       "bookmark-now",
  title:    "Bookmark This Link Now",
  contexts: ["link"]
}, null);

browser.contextMenus.onClicked.addListener(function(info, tab) {
  switch (info.menuItemId) {
    case "bookmark-now":
      browser.bookmarks.create(
        {
//        parentId: "",  // leaving this out uses default, which is good
//        title: "",     // How to set the title?
          url:   info.linkUrl
        }
      );
      break;
  }
});

info.linkText

I just figured that out myself! I don’t see how I missed it. Thanks.
So the final version (in background.js) is this:

function onBookmarkNowCreate() {
  browser.contextMenus.onClicked.addListener(function(info, tab) {
    switch (info.menuItemId) {
      case "bookmark-now":
        browser.bookmarks.create(
          {
            title: info.linkText,
            url:   info.linkUrl
          }
        );
        break;
    }
  });
}

browser.contextMenus.create({
  id:       "bookmark-now",
  title:    "Bookmark This Link Now",
  contexts: ["link"]
}, onBookmarkNowCreate);

Why use the onBookmarkNowCreate callback? You should just register the onClicked listener on top of the file without putting it into callback.
Not only it’s not necessary, it also won’t work in the upcoming MV3 where all event handlers must be registered synchronously.

1 Like

Thanks. I wondered what that callback was for and assumed it was for that. I originally registered the listener at file scope. I’ll move it back. What’s the purpose of that callback?

Creating a new menu is an asynchronous operation so the callback is there to tell you that it’s done. But it’s optional parameter so unless you need it, it’s best to simply omit it.

This is actually pretty rare because most (if not all) asynchronous API for addons returns a Promise and doesn’t use callbacks. And there is already bug for it: