How to Create A Chrome Extension in HTML CSS & JavaScript

1

Create Color Picker Chrome Extension in HTML CSS & JavaScript

Creating a Chrome extension can be a useful learning project, as it allows you to practice your skills in web development and get a better understanding of how Chrome extensions work. While the idea of creating an extension may seem complex at first, the process becomes much simpler once you understand the basic structure.

Chrome extensions are small programs that can customize and enhance the browser’s functionality. They are built using web technologies such as HTML, CSS, and JavaScript, and they can be easily installed from the Chrome Web Store.

In this blog, we will guide you through the process of creating a functional Color Picker extension for Chrome. By the end of this blog, you will have an extension that allows users to easily pick any color on the screen, view a history of picked colors, and copy or clear them with a single click.

Video Tutorial of Color Picker Chrome Extension

If you prefer visual learning, you can watch a given YouTube video that demonstrates how to create a color-picker Chrome extension using HTML, CSS, and JavaScript. Alternatively, you can continue reading this blog for a written guide on the same topic.

Steps to Create Color Picker Chrome Extension

We will create a color picker Chrome extension using HTML, CSS, and JavaScript in five simple steps:

  • Setting up the project
  • Creating the extension
  • Creating a manifest file
  • Testing and debugging
  • Publishing the extension

1. Setting up the project

In the initial step, we will create a new directory for our extension. This directory can be given any name you want, and make the index.html, style.css, and script.js files inside it. These files will contain the HTML, CSS, and JavaScript code for your extension.

Once you have made these files, you can proceed to the next step of creating your color picker extension.

2. Creating the extension

In the second step, we will design the user interface for our color picker extension and style it using HTML and CSS. Once the user interface is complete, we will use JavaScript to add color-picking functionality to the extension.

In the index.html file, add the following HTML code to create the basic structure of the extension:

<!DOCTYPE html>
<!-- Coding By CodingNepal - youtube.com/codingnepal -->
<html lang="en">
  <head>
    <link rel="stylesheet" href="style.css">
    <script src="script.js" defer></script>
  </head>
  <body>
    <div class="popup">
      <div class="picker">
        <button id="color-picker">Pick Color</button>
      </div>
      <div class="picked-colors hide">
        <header>
          <p class="title">Picked colors</p>
          <span class="clear-all">Clear All</span>
        </header>
        <ul class="all-colors"></ul>
      </div>
    </div>
  </body>
</html>

In the style.css file, add the following CSS code to add styles and make the extension visually appealing. If you want, you can change the color, background, font, and size of the extension in this code.

/* Import Google font - Poppins */
@import url('https://fonts.googleapis.com/css2?family=Poppins:[email protected];500;600&display=swap');
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: "Poppins", sans-serif;
}
.popup {
  width: 350px;
  background: #fff;
}
.popup :where(.picker, header, .all-colors) {
  display: flex;
  align-items: center;
}
.popup .picker {
  padding: 30px 0;
  background: #E3F2FD;
  justify-content: center;
}
.picker #color-picker {
  border: none;
  outline: none;
  color: #fff;
  font-size: 1rem;
  cursor: pointer;
  padding: 10px 20px;
  border-radius: 5px;
  background: #5372F0;
  transition: 0.3s ease;
}
#color-picker:hover {
  background: #2c52ed;
}
.picked-colors {
  margin: 10px 15px;
}
.picked-colors header {
  justify-content: space-between;
}
header .title {
  font-size: 1rem;
}
header .clear-all {
  cursor: pointer;
  font-size: 0.9rem;
  color: #5372F0;
}
header .clear-all:hover {
  color: #143feb;
}
.picked-colors.hide {
  display: none;
}
.picked-colors .all-colors {
  flex-wrap: wrap;
  list-style: none;
  margin: 10px 0 15px;
}
.all-colors .color {
  display: flex;
  cursor: pointer;
  margin-bottom: 10px;
  width: calc(100% / 3);
}
.all-colors .rect {
  height: 21px;
  width: 21px;
  display: block;
  margin-right: 8px;
  border-radius: 5px;
}
.all-colors .color span {
  font-size: 0.96rem;
  font-weight: 500;
  text-transform: uppercase;
  font-family: "Open sans";
}

In the script.js file, add the following JavaScript code to add functionality to the color picker extension. You can learn about the use of a particular line by reading the comments on each JavaScript line.

const colorPickerBtn = document.querySelector("#color-picker");
const clearAll = document.querySelector(".clear-all");
const colorList = document.querySelector(".all-colors");
const pickedColors = JSON.parse(localStorage.getItem("picked-colors") || "[]");

// Copying the color code to the clipboard and updating the element text
const copyColor = (elem) => {
    elem.innerText = "Copied";
    navigator.clipboard.writeText(elem.dataset.color);
    setTimeout(() => elem.innerText = elem.dataset.color, 1000);
}

const showColor = () => {
    if(!pickedColors.length) return; // Returning if there are no picked colors
    colorList.innerHTML = pickedColors.map(color => `
        <li class="color">
            <span class="rect" style="background: ${color}; border: 1px solid ${color == "#ffffff" ? "#ccc": color}"></span>
            <span class="value hex" data-color="${color}">${color}</span>
        </li>
    `).join(""); // // Generating li for the picked color and adding it to the colorList
    document.querySelector(".picked-colors").classList.remove("hide");

    // Add a click event listener to each color element to copy the color code
    document.querySelectorAll(".color").forEach(li => {
        li.addEventListener("click", e => copyColor(e.currentTarget.lastElementChild));
    });
}
showColor();

const activateEyeDropper = () => {
    document.body.style.display = "none";
    setTimeout(async () => {
        try {
            // Opening the eye dropper and getting the selected color
            const eyeDropper = new EyeDropper();
            const { sRGBHex } = await eyeDropper.open();
            navigator.clipboard.writeText(sRGBHex);

            // Adding the color to the list if it doesn't already exist
            if(!pickedColors.includes(sRGBHex)) {
                pickedColors.push(sRGBHex);
                localStorage.setItem("picked-colors", JSON.stringify(pickedColors));
                showColor();
            }
        } catch (error) {
            alert("Failed to copy the color code!");
        }
        document.body.style.display = "block";
    }, 10);
}

// Clearing all picked colors, updating local storage, and hiding the colorList element
const clearAllColors = () => {
    pickedColors.length = 0;
    localStorage.setItem("picked-colors", JSON.stringify(pickedColors));
    document.querySelector(".picked-colors").classList.add("hide");
}

clearAll.addEventListener("click", clearAllColors);
colorPickerBtn.addEventListener("click", activateEyeDropper);

3. Creating a manifest file

In the third step, we will create a manifest.json file for our extension. This file is a required part of every Chrome extension and serves as a configuration file for the extension. It contains information about the extension, such as its name, description, version, icons, and permissions.

To create the manifest.json file, create a new file in the project directory and name it manifest.json. Then, add the following code to the file:

{
    "manifest_version": 3,
    "name": "Color Picker",
    "description": "A simple color picker extension. Easily pick any color on the screen, view a history of picked colors, and copy or clear them with a single click.",
    "version": "1.0",
    "action": {
        "default_popup": "index.html"
    },
    "icons": {
        "16": "icons/icon16.png",
        "32": "icons/icon32.png",
        "48": "icons/icon48.png",
        "128": "icons/icon128.png"
    }
}

You can download a set of icons for the color picker extension from this Google Drive link. Once downloaded, change the folder name to  icons and add it to the project directory of your extension.

4. Testing and Debugging

In the fourth step, we’ll load our extension into Chrome from our local directory for testing and debugging purposes. To do this, follow these steps:

  • Open Chrome and go to this URL: chrome://extensions.
  • Enable the “Developer mode” toggle in the top-right corner of the page.
  • Click the “Load unpacked” button and select your extension project directory.
  • Your extension should now be loaded and appeared on the Chrome extensions page.

Testing and Debugging the Extension

To test the extension, click the extension icon in the Chrome toolbar and make sure that the color picker’s UI appears as expected and functionality works correctly.

If you encounter any issues or errors, you can use the Chrome DevTools console to debug the extension. To open DevTools, right-click on the extension popup and select “Inspect” option. You’ll also see Errors button right after the remove button for your extension.

Before publishing your extension to the Chrome Web Store or making it publicly available, it is essential to thoroughly test and debug it to ensure that it is functioning correctly.

5. Publishing the extension

In the final step, we will publish our color picker extension to the Chrome Web Store so that it can available to all users of Chrome. To do this, follow these steps:

  • Create a zip file of your extension and go to the Chrome Developer Dashboard.
  • Click the “Add new item” button and select the “Extension” option.
  • Fill out the required fields, including the name, description, and categories for your extension.
  • Upload the manifest.json file and the required icons for the extension.
  • Submit the extension for review.

Publishing your extension to the Chrome Web Store is a great way to showcase your skills as a developer and share your work with a wide audience. If you encounter any issues or problems during the publishing process, you can refer to the official documentation from Google for guidance.

Conclusion and Final Words

By following the steps in this blog, you’ve successfully created a functional color picker extension that allows users to easily select colors from the screen. This extension is compatible with all Chromium-based web browsers, including Chrome, Microsoft Edge, Opera, etc.

This project was a great opportunity to practice your web development skills and learn more about how Chrome extensions work. We hope that you enjoyed the process and feel more confident in your ability to create extensions in the future.

If you found this blog helpful, please consider sharing it with others. Your support helps us continue creating valuable content and resources for the development community. Thank you for your support!

 

Previous articleCreate A Budget Tracker in HTML CSS & JavaScript
Next article10 Must-Have Chrome Extensions for Web Developers

1 COMMENT

LEAVE A REPLY

Please enter your comment!
Please enter your name here