the-geeky-codes-high-resolution-logo-color-on-transparent-background geeky code red logo
  • Home
  • AI
    AIShow More
    generate vector icons
    Generate Vector Icons with ChatGPT DALLE 3: A Comprehensive Guide
    14 Min Read
    Dalle 3
    Dalle 3: A Step-by-Step Guide to Mastering AI Art Generation
    4 Min Read
    5 Best AI Tools to Convert Images to Video Animations
    5 Best AI Tools to Convert Images to Video Animations
    8 Min Read
    Exploring the Impressive Mistral 7B Model
    Exploring the Impressive Mistral 7B Model for Text Summarization and Coding
    6 Min Read
    The AI Revolution this week
    Must Read – The AI Revolution this week 30 Sep 2023: Integrating AI Tools into Everyday Life
    6 Min Read
  • Tutorial
    • React js
    • Python
    • Javascript
  • AI Tools
Reading: Build an Internet Speed Test Chrome Extension
Share
the geeky codesthe geeky codes
Aa
  • AI
  • AI Tools
  • Javascript
  • Python
  • React js
  • Advertise
Search
  • Categories
    • AI
    • AI Tools
    • Javascript
    • Python
    • React js
  • More
    • Advertise
Follow US
Copyright ©2023 The Geeky codes. All Rights Reserved.
the geeky codes > Blog > Tutorial > Javascript > Build an Internet Speed Test Chrome Extension
TutorialJavascript

Build an Internet Speed Test Chrome Extension

thegeekycodes By thegeekycodes 22 September 2023 11 Min Read
Internet Speed Test Chrome Extension
SHARE

Intro – Internet Speed Test Chrome Extension

Internet Speed Test Chrome Extension helps Chrome users to test the current internet speed. Here’s a breakdown of the necessary components and how to build it, while ensuring your extension is primed for search engine success.

Contents
Intro – Internet Speed Test Chrome ExtensionEssential Components of the Internet Speed Test ExtensionSet up the project structure:Coding TimeManifest FileTheme SwitcherComplete CodeUI – Popup.htmlHow to Use and Test the InternetSpeedTest ExtensionUsing the InternetSpeedTest Extension:Testing the InternetSpeedTest Extension:

Chrome extensions enhance the browsing experience. Whether it’s blocking ads, managing passwords, or, in our case, checking internet speeds, these extensions offer additional features to the standard Chrome functionality.

Essential Components of the Internet Speed Test Extension

We’ll be using HTML, CSS, and JavaScript for this task. Let’s get started:

Set up the project structure:

The Folder structure looks like below

Create a new folder for your extension and name it something like “screenshot-extension.” Inside this folder, create the following files:

  • manifest.json: This file contains metadata about the extension.
  • popup.html: This file will display the extension’s popup.
  • popup.js: This file will contain the JavaScript code for taking the screenshot.
  • style.css: This file will contain the CSS for styling the popup. Here’s a simplified folder structure for your screenshot Chrome extension

Coding Time

Manifest File

The manifest file serves as the backbone of any Chrome extension. For our InternetSpeedTest, the manifest uses version 3, the latest and most secure.

// manifest.json
{
    "manifest_version": 3,
    "name": "InternetSpeed test",
    "version": "1.0",
    "description": "Monitors your internet connection speed",
    "permissions": ["activeTab"],
    "background": {
        "service_worker": "js/background.js"
    },
    "action": {
        "default_popup": "popup.html",
        "default_icon": {
            "48": "icons/logo48.png"
        }
    },
    "host_permissions": ["http://*/*", "https://*/*"],
    "icons": {
        "48": "icons/logo48.png"
    }
}

Key Elements:

  • manifest_version: Indicates the version of the manifest file format. Version 3 offers improved security and performance.
  • name: The title of your extension, which users will see in the Chrome Web Store and in their extensions page.
  • permissions: Lists the various Chrome APIs the extension might access.
  • background: Defines a background script that remains running as long as the extension is active.
  • action: Determines the UI component of the extension. Here, a popup is defined, which displays when users click on the extension icon.
  • host_permissions: Specifies the websites the extension can access.

And there are other essential elements like icons and versioning.

Theme Switcher

While the manifest provides the structure, the JavaScript dictates functionality. For instance, one core feature is toggling between dark and light themes:

document.getElementById("themeToggle").addEventListener("click", () => {
    const bodyElement = document.body;

    // Check if current theme is dark
    if (bodyElement.classList.contains("bg-gray-900")) {
        bodyElement.classList.remove("bg-gray-900", "text-gray-100");
        bodyElement.classList.add("bg-gray-100", "text-gray-900");
    } else {
        bodyElement.classList.remove("bg-gray-100", "text-gray-900");
        bodyElement.classList.add("bg-gray-900", "text-gray-100");
    }
});

Actual speed-checker function, which fetches a file from freetestdata.com (downloading 1MB file) to determine the internet speed:

const TEST_FILE_URL =
    "https://freetestdata.com/wp-content/uploads/2021/09/1-MB-DOC.doc";
const TEST_FILE_SIZE_MB = 1; // Size of your test file in MB

document.getElementById("checkSpeed").addEventListener("click", () => {
    const spinner = document.getElementById("spinner");
    const speedInfo = document.getElementById("speedInfo");

    spinner.classList.remove("hidden"); // Show spinner
    speedInfo.innerText = "-"; // Reset speed info

    const startTime = new Date().getTime();
    // A start time is recorded using new Date().getTime(), which gives the current time in milliseconds.
    //Then, the script fetches a test file from a given TEST_FILE_URL. The "?nocache=" + startTime appended
    // to the URL ensures that the file is fetched fresh every time (preventing caching).
    fetch(TEST_FILE_URL + "?nocache=" + startTime)
        .then((response) => response.blob())
        .then((blob) => {
            const endTime = new Date().getTime();
            const durationSeconds = (endTime - startTime) / 1000;
            const speedMbps = (TEST_FILE_SIZE_MB / durationSeconds).toFixed(2);
            speedInfo.innerText = `${speedMbps} Mbps`;
            spinner.classList.add("hidden"); // Hide spinner after fetching
        })
        .catch((error) => {
            speedInfo.innerText = "Error!";
            console.error("Error fetching test file:", error);
            spinner.classList.add("hidden"); // Hide spinner on error
        });
});

Complete Code

const TEST_FILE_URL =
    "https://freetestdata.com/wp-content/uploads/2021/09/1-MB-DOC.doc";
const TEST_FILE_SIZE_MB = 1; // Size of your test file in MB
const themeToggleButton = document.getElementById("themeToggle");

document.getElementById("themeToggle").addEventListener("click", () => {
    const bodyElement = document.body;

    // Check if current theme is dark
    if (bodyElement.classList.contains("bg-gray-900")) {
        bodyElement.classList.remove("bg-gray-900", "text-gray-100");
        bodyElement.classList.add("bg-gray-100", "text-gray-900");
    } else {
        bodyElement.classList.remove("bg-gray-100", "text-gray-900");
        bodyElement.classList.add("bg-gray-900", "text-gray-100");
    }
});

document.getElementById("buymeacoffee").addEventListener("click", () => {
    window.open("https://www.buymeacoffee.com/yourusername", "_blank");
});

document.getElementById("checkSpeed").addEventListener("click", () => {
    const spinner = document.getElementById("spinner");
    const speedInfo = document.getElementById("speedInfo");

    spinner.classList.remove("hidden"); // Show spinner
    speedInfo.innerText = "-"; // Reset speed info

    const startTime = new Date().getTime();
    // A start time is recorded using new Date().getTime(), which gives the current time in milliseconds.
    //Then, the script fetches a test file from a given TEST_FILE_URL. The "?nocache=" + startTime appended
    // to the URL ensures that the file is fetched fresh every time (preventing caching).
    fetch(TEST_FILE_URL + "?nocache=" + startTime)
        .then((response) => response.blob())
        .then((blob) => {
            const endTime = new Date().getTime();
            const durationSeconds = (endTime - startTime) / 1000;
            const speedMbps = (TEST_FILE_SIZE_MB / durationSeconds).toFixed(2);
            speedInfo.innerText = `${speedMbps} Mbps`;
            spinner.classList.add("hidden"); // Hide spinner after fetching
        })
        .catch((error) => {
            speedInfo.innerText = "Error!";
            console.error("Error fetching test file:", error);
            spinner.classList.add("hidden"); // Hide spinner on error
        });
});
// background.js

UI – Popup.html

Styled with the Tailwind CSS framework, it features a responsive design. The main elements include a toggle for switching between light and dark themes, a ‘Buy me a coffee’ button, and a prominent ‘Check Now’ button that initiates the speed test. While testing, a spinning loader appears, and once the test is complete, the speed result displays prominently on the screen.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <link
            href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css"
            rel="stylesheet"
        />
        <link href="css/style.css" rel="stylesheet" />
        <script src="js/popup.js" defer></script>
        <title>InternetSpeedTest</title>
    </head>
    <body
        class="bg-gray-100 dark:bg-gray-900 text-gray-900 dark:text-gray-100 body mx-auto"
        data-theme="light"
    >
        <div class="p-4">
            <header class="flex justify-between items-center mb-4">
                <h1 class="text-xl font-bold">Speed Checker</h1>
                <div class="space-x-2">
                    <button
                        id="themeToggle"
                        class="bg-blue-500 hover:bg-blue-600 px-4 py-2 rounded"
                    >
                        Toggle Theme
                    </button>
                    <button
                        id="buymeacoffee"
                        class="bg-yellow-400 hover:bg-yellow-500 px-4 py-2 rounded"
                    >
                        Buy me a coffee
                    </button>
                </div>
            </header>
            <div class="mb-4 p-4 bg-white dark:bg-gray-800 shadow-lg rounded">
                <p class="text-center text-lg mb-3">Check Your Speed</p>
                <div class="flex flex-col items-center space-y-3">
                    <button
                        id="checkSpeed"
                        class="bg-green-500 hover:bg-green-600 text-white px-6 py-2 rounded"
                    >
                        Check Now
                    </button>
                    <div id="spinner" class="hidden">
                        <svg
                            class="animate-spin h-6 w-6 text-blue-500"
                            xmlns="http://www.w3.org/2000/svg"
                            fill="none"
                            viewBox="0 0 24 24"
                        >
                            <circle
                                class="opacity-25"
                                cx="12"
                                cy="12"
                                r="10"
                                stroke="currentColor"
                                stroke-width="4"
                            ></circle>
                            <path
                                class="opacity-75"
                                fill="currentColor"
                                d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
                            ></path>
                        </svg>
                    </div>
                    <div
                        id="speedInfo"
                        class="text-3xl text-center bg-clip-text text-transparent bg-gradient-to-r from-blue-500 to-pink-500 font-bold"
                    >
                        -
                    </div>
                </div>
            </div>
        </div>
    </body>
</html>

💁 Check out our other articles😃

 👉  Generate a free Developer Portfolio website with AI prompts

 👉  Fix Spelling Mistakes in Python Like a Pro!

How to Use and Test the InternetSpeedTest Extension

Using the InternetSpeedTest Extension:

  1. Installation: Once you’ve added the extension to Chrome, you’ll notice the icon (a visual representation of the extension) in the browser’s toolbar. This icon serves as the primary interaction point.
  2. Test Internet Speed:
    • Click on the extension icon in the toolbar. A popup will appear, featuring a button labeled “Check Now”.
    • Click this button. A spinner indicates that the test is in progress.
    • Once complete, your connection speed will be displayed in Mbps. If there’s an error, the extension will notify you.
  3. Toggle Theme: In the same popup, you’ll notice a “Toggle Theme” button. Clicking this alternates between light and dark modes, catering to your visual preference.
  4. Support the Developer: If you love the extension and wish to support its ongoing development, click the “Buy me a coffee” button, which redirects you to a donation page.

Testing the InternetSpeedTest Extension:

Before you publish your extension or release updates, it’s crucial to test thoroughly. Here’s a simple guide:

  1. Load the Extension Locally:
    • Open Chrome and go to chrome://extensions/.
    • Enable “Developer mode” at the top right.
    • Click “Load unpacked” and select the directory where your extension files are stored. This loads your extension directly into Chrome for testing.
  2. Test Functionality:
    • Click the extension icon and run the speed test multiple times. Ensure consistent and accurate results.
    • Toggle between themes and check for visual inconsistencies or errors.
    • Click the “Buy me a coffee” link to ensure it redirects correctly.
  3. Check Error Logs: While on the chrome://extensions/ page, under your extension, click “Inspect”. This opens the Chrome Developer Tools specific to your extension, displaying any errors or logs.
  4. Test on Multiple Devices: If possible, test the extension on different devices and screen sizes to ensure it’s responsive and functional across all platforms.
  5. Collect Feedback: Share your extension with friends or colleagues and collect feedback. They might spot issues or provide insights you hadn’t considered.
  6. Update and Iterate: Based on the testing results, make necessary changes. It’s better to identify and resolve issues now rather than after hundreds or thousands have downloaded your extension.

Sign Up For Daily Newsletter

Be keep up! Get the latest breaking news delivered straight to your inbox.
By signing up, you agree to our Terms of Use and acknowledge the data practices in our Privacy Policy. You may unsubscribe at any time.
Share This Article
Facebook Twitter Copy Link Print
Previous Article Tableau - Basic to Advanced Free Course – Tableau – Basic to Advanced
Next Article Mastering Adobe Photoshop's Generative Fill Free Course – Mastering Adobe Photoshop’s Generative Fill
Leave a comment

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Twitter Follow
Telegram Follow

Subscribe Now

Subscribe to our newsletter to get our newest articles instantly!

Most Popular
Advanced Routing Techniques in Nextjs 15
Advanced Routing Techniques in Next js 15
20 November 2024
Attachment Details Image-to-Text-Converter-with-Claude-Nextjs-15
Building an AI-Powered Image-to-Text Converter with Claude, Next.js 15, and Vercel AI SDK
20 November 2024
Generate-Dynamic-OpenGraph-Images-in-Nextjs15
How to Generate Dynamic OpenGraph Images in Next.js App Router 15 with TypeScript
20 November 2024
Google Analytics 4 in Nextjs 14
How to Install Google Analytics 4 in Next.js 15 (App Router) with TypeScript [2024]
20 November 2024
docker compose
Getting Started with Docker Compose
20 November 2024

You Might Also Like

Advanced Routing Techniques in Nextjs 15
TutorialNextjs

Advanced Routing Techniques in Next js 15

7 Min Read
Attachment Details Image-to-Text-Converter-with-Claude-Nextjs-15
TutorialNextjs

Building an AI-Powered Image-to-Text Converter with Claude, Next.js 15, and Vercel AI SDK

4 Min Read
Generate-Dynamic-OpenGraph-Images-in-Nextjs15
TutorialNextjs

How to Generate Dynamic OpenGraph Images in Next.js App Router 15 with TypeScript

9 Min Read
Google Analytics 4 in Nextjs 14
TutorialNextjs

How to Install Google Analytics 4 in Next.js 15 (App Router) with TypeScript [2024]

6 Min Read

Always Stay Up to Date

Subscribe to our newsletter to get our newest articles instantly!

the geeky codes geeky code red logo

Providing valuable resources for developers in the form of code snippets, software tutorials, and AI related content.

About

  • About Us
  • Contact
  • Terms and Conditions
  • Privacy Policy
  • Disclaimer
  • Affiliate Disclosure

Resource

  • The Art of AI Prompt Engineering: Crafting Effective Inputs for AI Models

Get the Top 10 in Search!

Looking for a trustworthy service to optimize the company website?
Request a Quote
© 2023 The Geeky Codes. All Rights Reserved
We are happy to see you join Us!

🔥📢Subscribe to our newsletter and never miss our latest code snippets, tutorials and AI updates

Zero spam, Unsubscribe at any time.
Welcome Back!

Sign in to your account

Lost your password?