AI2023-09-07

How to Use CodeWhisperer to Build a Browser Extension

Learn how to use the power of CodeWhisperer to develop a browser extension in 7 easy steps, and supercharge your online experience.
How to Use CodeWhisperer to Build a Browser Extension

Browser extensions have become an integral part of our online experience, enabling us to enhance and customize our browsers to better suit our needs. In this article, we will explore how I used CodeWhisperer, a powerful development tool, to build a simple browser extension. We'll build a basic extension that allows users to highlight and bookmark text on web pages. Throughout this article, I will provide step-by-step instructions and share the complete code for the extension.

CodeWhisperer, a robust development tool, designed to empower developers with insights, suggestions, and real-time assistance. CodeWhisperer streamlines the coding process and elevates the final product's quality.

Setting the Stage: Planning the Browser Extension's Functionality

The project described is about building a browser extension using the Browser Highlighter. The extension's purpose is to allow users to highlight and bookmark text on web pages they are browsing. The extension provides a simple user interface in the form of a popup, where users can interact with buttons to perform these actions.

Here's a breakdown of the main features of the extension:

1. Text Highlighter

Users can select text on a web page and then click the "Highlight" button in the extension popup. This action triggers the extension to capture the selected text and display it in an alert.

2. Bookmark Page

Users can click the "Bookmark" button in the extension popup to capture the title and URL of the current web page. The extension then displays this information in an alert.

The extension uses a combination of HTML, CSS, and JavaScript to achieve its functionality. The manifest file (manifest.json) provides the necessary metadata and permissions for the extension to work correctly. The popup HTML (popup.html) creates the user interface for interaction, while the popup JavaScript (popup.js) handles the logic behind the buttons.

Additionally, a content script (content.js) is included in the extension, although it doesn't perform any active tasks in this simple example. Content scripts are used to inject JavaScript code into web pages, allowing the extension to interact with and modify the content of the loaded pages.

In this endeavor, I embarked on the creation of a browser extension with a specific focus: enabling users to highlight and bookmark text on web pages. This simple yet practical functionality offers users a convenient way to interact with the content they encounter during their browsing sessions. The project aimed to demonstrate the potential of CodeWhisperer in developing browser extensions and showcase its impact on the development workflow.

Prerequisites

Before we dive into building the extension, make sure you have the following prerequisites:

  1. A text editor or Integrated Development Environment (IDE) of your choice.
  2. Basic knowledge of HTML, CSS, and JavaScript.
  3. A compatible web browser (Chrome, Firefox, etc.) for testing the extension.

Write Your Extension with CodeWhisperer

The first step in crafting the extension was to create a manifest file. This file, named manifest.json, outlined essential details about the extension, such as its name, version, description, permissions, and icons. 

With CodeWhisperer's assistance, the process was remarkably smooth, as the tool offered auto-completions and real-time validation, ensuring the correct structure of the manifest.

With the foundation in place, I moved on to constructing the extension's user interface. Using HTML and CSS, I designed a simple popup window that hosted the extension's functionality. CodeWhisperer continued to prove its worth by suggesting HTML elements and CSS properties, aiding in the creation of an aesthetically pleasing and functional interface.

Step 1: Project Setup

To start, create a new directory for your project and navigate to it in your terminal or command prompt:

mkdir webExtension
cd webExtension

Step 2: Create the Manifest File

Every browser extension requires a manifest file that provides important information about the extension. Create a file named manifest.json in your project directory with the following content:

{
  "manifest_version": 2,
  "name": "Browser Highlighter",
  "version": "1.0",
  "description": "Highlight and bookmark text on web pages",
  "permissions": ["activeTab"],
  "browser_action": {
    "default_popup": "popup.html",
    "default_icon": {
      "16": "images/icon16.png",
      "48": "images/icon48.png",
      "128": "images/icon128.png"
    }
  },
  "icons": {
    "16": "images/icon16.png",
    "48": "images/icon48.png",
    "128": "images/icon128.png"
  },
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["content.js"]
    }
  ]
}

This manifest file defines the extension's basic details, including its name, version, description, icons, and permissions.

Step 3: Build the Popup HTML

The extension will have a popup that allows users to interact with it. Create a file named popup.html in your project directory with the following content:

<!DOCTYPE html>
<html>
<head>
  <title>Browser Highlighter</title>
  <style>
    body {
      width: 200px;
      padding: 10px;
    }
  </style>
</head>
<body>
  <h1>Highlighter</h1>
  <button id="highlightButton">Highlight</button>
  <button id="bookmarkButton">Bookmark</button>
  <script src="popup.js"></script>
</body>
</html>

Step 4: Write the Popup JavaScript

Create a file named popup.js in your project directory with the following content:

document.addEventListener('DOMContentLoaded', function() {
  const highlightButton = document.getElementById('highlightButton');
  const bookmarkButton = document.getElementById('bookmarkButton');

  highlightButton.addEventListener('click', function() {
    chrome.tabs.executeScript({
      code: 'document.getSelection().toString();',
    }, function(selectedText) {
      alert('Highlighted Text: ' + selectedText[0]);
    });
  });

  bookmarkButton.addEventListener('click', function() {
    chrome.tabs.executeScript({
      code: 'document.title',
    }, function(title) {
      chrome.tabs.executeScript({
        code: 'document.URL',
      }, function(url) {
        alert('Bookmark Title: ' + title[0] + '\nBookmark URL: ' + url[0]);
      });
    });
  });
});

This script adds functionality to the buttons in the popup. The highlightButton extracts and alerts the selected text, while the bookmarkButton alerts the current page's title and URL.

Step 5: Create the Content Script

Create a file named content.js in your project directory with the following content:

console.log('Content script loaded.');

Step 6: Add Icon Images

Create a directory named images in your project directory and place the icon images (icon16.png, icon48.png, and icon128.png) inside it.

Step 7: Load the Extension

To load the extension in your browser, follow these steps:

  1. Open your browser and go to the extensions management page.
  2. Enable "Developer mode."
  3. Click on "Load unpacked" or "Load extension" and select your project directory (webExtension).

Using CodeWhisperer for Code Reviews

As development progressed, I found CodeWhisperer's real-time suggestions and insights to be invaluable. Not only did the tool provide automatic error detection, but it also suggested improvements to my code. This aspect proved crucial during the code review process, enabling me to catch potential issues early and adhere to best practices.

My experience with CodeWhisperer was transformative. The tool not only accelerated the development process but also instilled a sense of confidence in the code I produced. The real-time assistance and insights not only improved code quality but also deepened my understanding of certain programming concepts.

Overcoming Challenges and Roadblocks

No development journey is without its challenges, and this project was no exception. While implementing certain features, I encountered roadblocks that required careful consideration. CodeWhisperer, with its code suggestions and comprehensive documentation references, helped me overcome these hurdles efficiently.

Streamline Your Coding Process with CodeWhisperer

In conclusion, the journey of building a browser extension using CodeWhisperer was an enlightening experience. The tool's impact was evident from project initiation to completion, offering guidance, suggestions, and validation at every step. This project serves as a testament to CodeWhisperer's ability to enhance the development process and empower developers to create robust, efficient, and high-quality code. As the digital landscape continues to evolve, tools like CodeWhisperer stand as vital companions for programmers aiming to push the boundaries of innovation.

Feel free to experiment with the code and extend the functionality of the extension to further enhance your browsing experience!

Subscribe to the Hatica blog for more insights on AI, developer productivity, and engineering effectiveness.

Share this article:
Table of Contents
  • Setting the Stage: Planning the Browser Extension's Functionality
  • 1. Text Highlighter
  • 2. Bookmark Page
  • Prerequisites
  • Write Your Extension with CodeWhisperer
  • Step 1: Project Setup
  • Step 2: Create the Manifest File
  • Step 3: Build the Popup HTML
  • Step 4: Write the Popup JavaScript
  • Step 5: Create the Content Script
  • Step 6: Add Icon Images
  • Step 7: Load the Extension
  • Using CodeWhisperer for Code Reviews
  • Overcoming Challenges and Roadblocks
  • Streamline Your Coding Process with CodeWhisperer

Ready to dive in? Start your free trial today

Overview dashboard from Hatica