Extension – CodingNepal https://www.codingnepalweb.com CodingNepal is a blog dedicated to providing valuable and informative content about web development technologies such as HTML, CSS, JavaScript, and PHP. Thu, 11 May 2023 07:43:38 +0000 en-US hourly 1 https://wordpress.org/?v=6.4.2 How to Create A Chrome Extension in HTML CSS & JavaScript https://www.codingnepalweb.com/create-chrome-extension-html-css-javascript/ https://www.codingnepalweb.com/create-chrome-extension-html-css-javascript/#comments Wed, 04 Jan 2023 12:23:16 +0000 https://www.codingnepalweb.com/?p=3787 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:wght@400;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!

 

]]>
https://www.codingnepalweb.com/create-chrome-extension-html-css-javascript/feed/ 2
Create A Simple Chrome Extension in HTML CSS & JavaScript https://www.codingnepalweb.com/create-chrome-extension-html-javascript/ https://www.codingnepalweb.com/create-chrome-extension-html-javascript/#respond Sun, 01 Jan 2023 21:08:21 +0000 https://www.codingnepalweb.com/?p=4125 Create A Simple Chrome Extension in HTML CSS & JavaScript
Are you interested in creating your own Chrome extension but not sure where to start? Look no further! In this article, we will guide you through the process of creating a simple Chrome extension using HTML, CSS, and JavaScript.

Chrome extensions are small programs that modify web page behavior or add functionality to the browser. They are made of HTML, CSS, and JavaScript files that run in the browser and interact with web pages. Building a Chrome extension can be simple once you understand the basic structure, even if you’re new to web development.

In this blog, you will create a Chrome extension that changes the background color of a webpage. You will learn how to set up the basic structure of the extension, use JavaScript to interact with the web page’s DOM, and style the extension with CSS.

By the end of this blog, you will have a fully functional Chrome extension that you can customize and share with others. Whether you’re a beginner looking to learn the basics of web development or an experienced developer looking to add to your skill set, this blog is for you.

Steps to creating a Chrome Extension

We will create a simple Chrome extension in five easy steps. But you can also add additional features to your extension as desired.
  • Set up the basic structure
  • Add functionality
  • Style the extension
  • Test the extension
  • Package and publish it

1. Set up the basic structure of the extension

Before you can start building your Chrome extension, you need to set up the basic structure. This involves creating a manifest file and an HTML file for the extension’s interface.
First, create a new folder for your extension and add a file named “manifest.json” to it. The manifest file is a JSON file that defines the basic information about the extension, such as its name and version. Here is an example of a manifest file:
Manifest CODE:
 {
  "manifest_version": 3,
  "name": "My Extension",
  "version": "1.0",
  "description": "A simple extension that changes the background color of a webpage.",
  "background": {
    "service_worker": "background.js"
  },
  "action": {
    "default_popup": "popup.html"
  },
  "permissions": [
    "activeTab",
    "scripting",
    "storage"
  ]
}

The manifest file in an extension specifies its name, version, description, HTML interface file, and required permissions. In the example, the “scripting” and “storage” permissions are needed to store and change the webpage color through scripting.

Additionally, we can create a “background.js” file to set the basic settings of our extension. This is the first of two JavaScript files. The second will be “content.js,” where we will add all our functionality in step 2. Here, we set the color we want to change the extension to. An example might look like this:

Background.js CODE:
let color = '#FF0000'; // Can be any colour you want!

chrome.runtime.onInstalled.addListener(() => {
  chrome.storage.sync.set({ color });
});
Next, create an HTML file for the extension’s interface. This file will contain the HTML, CSS, and JavaScript code for the extension. For example:
HTML CODE:
<!DOCTYPE html>
<html>
<head>
  <!--<title>My Extension</title>-->
  <style>
    /* Add your CSS styles here */
  </style>
</head>
<body>
  <!-- Add your HTML content here -->
  <script src="scripts/content.js"></script>
</body>
</html>

In the HTML file, you can add any necessary CSS styles in the <style> element and add your HTML content in the <body> element. You can also include a JavaScript file in the <script> element, which can be used to add functionality to the extension.

A full HTML file might look like this:

HTML CODE:
<!DOCTYPE html>
<html>
  <head>
    <!--<title>My Extension</title>-->
    <style>
      /* Add your CSS styles here */
    </style>
  </head>
  <body>
    <!-- Add your HTML content here -->
    <center>
      <h1>Background Color Changer</h1>
      <button id="change-button" >Click Me</button>
      <!--<script src="scripts/content.js"></script>-->
    </center>
  </body>
</html>
That’s it for step 1! In total, you should have 4 files – “manifest.json”, “popup.html”, “background.js” and “content.js”. Now that you have the basic structure of your Chrome extension set up, you’re ready to start adding functionality and styling.

Add functionality to the extension using JavaScript

Now that you have the basic structure of your Chrome extension set up, you can start adding functionality to it using JavaScript. JavaScript allows you to interact with the DOM of the webpage and modify the behavior of the extension.

To add JavaScript to your extension, create a separate JavaScript file and include it in the “popup.html” file using the <script> element. In the main scripting file (“content.js”), you can add functionality to the extension’s button. For example, a simple function can be created to change the webpage’s background color when the button is clicked:

Content.js CODE:
// The actual function that will be executed to change the page color
function changeBackgroundColor() {
   chrome.storage.sync.get("color", ({ color }) => {
      document.body.style.backgroundColor = color;
   });
}
In this example, the changeBackgroundColor() function retrieves the stored color and changes the background color of the current webpage. The script listens for a click event and activates on the current tab in response. This is done using the following function:
Content.js CODE:
let changeColor = document.getElementById("change-button");

// Creates the event when the button is clicked to call the color changing
changeColor.addEventListener("click", async () => {
  let [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
  chrome.scripting.executeScript({
    target: { tabId: tab.id },
    function: changeBackgroundColor
  });
});
In this example, the event listener listens for clicks on elements with the class “button” and calls the changeBackgroundColor function when one is clicked.
These are just a few examples of what you can do with JavaScript in your Chrome extension. You can use it to access and manipulate elements on the webpage, communicate with the background script and other content scripts, and more.

3. Style the extension using CSS

You can use CSS to add visual styling and make it look more appealing. CSS is a stylesheet language that allows you to specify the look and feel of your HTML elements.
To add CSS to your extension, you can include it in the HTML file you created in step 1 or create a separate CSS file and include it using the <link> element. Here is an example of some simple CSS styles:
CSS CODE:
body {
   background-color: #fff;
   font-family: sans-serif;
}

#change-button {
  border: none;
  border-radius: 5px;
  padding: 10px 20px;
  color: #fff;
  font-size: 1rem;
  cursor: pointer;
  background: #5372F0;
}

#change-button:hover {
  background: #2c52ed;
}

In this example, the CSS styles define the body element’s background color and font family, as well as the appearance of elements with the class “button.” The styles use properties such as background color, border color, and color to specify the visual characteristics of the elements.

These simple changes give us the following look:

4. Test the extension

Before you can package and publish your Chrome extension, it’s important to test it to make sure it works as intended and debug any issues that arise. You can use the Chrome Developer Tools to test and debug your extension.

To first upload your extension to your browser, navigate to your extensions page, or go to this url: chrome://extensions/, and load the file containing all of your programs directly into your extensions page, using the “Load unpacked” button. Toggle the developer mode ON if you don’t see the “Load unpacked” button.

Create A Simple Chrome Extension in HTML CSS & JavaScript

If you have followed along with this guide, your extension should be able to do the following:
Test 20and 20Upload
If you encounter an error while testing your extension, you can use the console to identify and fix the problem. To open the browser console, press the F12 shortcut key or right-click on the extension popup and select the Inspect option.

5. Package and publish the extension

After you’ve built and tested your Chrome extension, you can package it into a .crx file and publish it to the Chrome Web Store. This will allow others to download and install the extension. But before publishing it, it will be good if you can add additional features to it and make it more useful for others.

If you want to create a more advanced and useful Chrome extension, you can check out my recently uploaded blog on How to Make Color Picker Chrome Extension in HTML CSS & JavaScript. This blog will guide you through the process of building a color picker extension for Chrome from scratch.

By making a useful extension, you can share it with a wider audience, which is a good way to showcase your skills as a developer and potentially monetize your extension through the store. Read the official Google article to publish your Chrome extension and make it publicly available.

Conclusion and Final Words

Creating your own Chrome extension can be a fun and rewarding experience, whether you’re doing it for fun, learning, or professional development. By following the steps in this guide, you can build a polished extension that can customize the behavior of web pages or add additional functionality to the browser.

By continuing to learn and improve your skills, you can make your Chrome extension even more powerful and useful for your users. LinkedIn Learning can be a reasonably priced course that provides a wealth of development resources.

Ultimately, there it is: you have your first basic Chrome extension up and running. The only thing left for you is to keep exploring and keep creating. If it was helpful to you, don’t forget to share it with others to help them benefit as well. Thank you!!

 

]]>
https://www.codingnepalweb.com/create-chrome-extension-html-javascript/feed/ 0