Build A Chrome Web Extension for Bookmark Sharing

Build A Chrome Web Extension for Bookmark Sharing

Enhancing website functionalities through custom features via web extensions is a powerful capability. From identifying CSS classes on HTML elements to executing actions based on specific events, the scope of possibilities is vast.

In this comprehensive guide, we will walk you through the process of creating a web extension tailored for bookmarking links. While the tutorial primarily focuses on the frontend aspects, setting up the backend is relatively straightforward and will be briefly discussed.

Before diving into the implementation, it's assumed that you possess a fundamental understanding of JavaScript. Additionally, as we'll be using Chrome for development and testing purposes, make sure you have Chrome installed and ready.

Let's get started:

Getting Started

Begin by creating a manifest.json file in your project directory. This file serves as the entry point and configuration file for your web extension. Below is the structure of the manifest file, utilizing Manifest version 3 syntax:

{
    "name": "Bookmark Sharer",
    "version": "1.0",
    "author": "Akachukwu Ogbonna",
    "description": "Share interesting links discovered on the internet, anonymously and securely.",
    "permissions": ["activeTab", "contextMenus", "notifications", "storage"],
    "icons": {
        "48": "icons/icon.png"
    },
    "action": {
        "default_icon": "icons/icon.png",
        "default_popup": "popup.html"
    },
    "background": {
        "service_worker": "js/background.js"
    },
    "host_permissions": [""],
    "manifest_version": 3
}

Explanation of the configurations:

  • name: Name of the extension.

  • version: Version number.

  • author: Creator's name.

  • description: Brief description of the extension's functionality.

  • permissions: Required permissions.

  • icons: Icon used for the extension.

  • action: Configuration for default icon and popup HTML.

  • background: Definition of background script (service worker).

  • host_permissions: Access permissions for URLs.

  • manifest_version: Manifest file format version.

Create the necessary directory structure as follows:

project_directory/
├── icons/
│   └── icon.png
├── js/
│   └── background.js
├── manifest.json
├── popup.html
└── README.md

Functionality

The logic of our extension resides in background.js. Our objective is to display a context menu button on right-click, capturing the page's URL upon clicking and sending it for storage.

Below is the implementation in background.js:

chrome.runtime.onInstalled.addListener(function () {
  console.log('Bookmark Sharer installed');
});

chrome.contextMenus.removeAll(function () {
  chrome.contextMenus.create({
    title: 'Share Link',
    contexts: [
      'page',
      'frame',
      'selection',
      'link',
      'editable',
      'image',
      'video',
      'audio',
      'browser_action',
      'page_action',
    ],
    id: 'performAction',
  });
});

chrome.contextMenus.onClicked.addListener(async function (info, tab) {
  if (info.menuItemId === 'performAction') {
    const url = tab.url  (info.linkUrl  info.srcUrl || info.pageUrl);
    if (url) {
      await handleShare(url);
    } else {
      console.error('Error: Unable to retrieve the URL.');
    }
  }
});

async function handleShare(url) {
  try {
    const urlEndpoint = 'https://mio-u5uy.onrender.com/links';
    const res = await fetch(urlEndpoint, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        link: url,
      }),
    });
    if (!res.ok) throw new Error(`HTTP error! Status: ${res.status}`);
    console.log('Link shared successfully!');
  } catch (error) {
    console.error('Error sharing the link. Please try again.', error);
  }
}

Explanation of the code:

  • chrome.runtime.onInstalled.addListener: Event listener triggered upon extension installation.

  • chrome.contextMenus.removeAll and chrome.contextMenus.create: Creation of the "Share Link" context menu item.

  • chrome.contextMenus.onClicked.addListener: Response to clicks on context menu items, triggering URL capture and sharing.

  • handleShare function: Handles sharing of the URL, sending a POST request to the specified endpoint.

Testing Instructions

  1. Navigate to chrome://extensions.

  2. Visit any web page you wish to share or bookmark.

  3. Install the extension from the directory.

  4. Right-click anywhere on the page to open the context menu.

  5. Select "Share Link" to capture the URL for sharing.

With these steps completed, you now have a functional Chrome web extension for easy link sharing.

Conclusion

I trust that this guide has equipped you with the knowledge and tools necessary to craft your own web extension tailored for link bookmarking. By following the steps outlined herein, you've learned how to create a functional extension capable of enhancing your browsing experience.

As you delve deeper into the world of web extensions, you'll discover endless possibilities for customization and optimization. Feel free to experiment with different functionalities and adapt the extension to suit your unique needs and preferences.

Happy bookmarking!