Creating a Custom Browser Automation Extension: A Step-by-Step Guide

Table of Contents

Introduction

This guide walks you through the step-by-step process of building a simple browser automation extension. You will learn which files to set up, how to load the extension into your browser, and how to integrate it with a local batch file via a Node.js backend.

Do you wonder why you need a custom browser automation extension?

You can save hours of manual work with Browser extension, but off-the-shelf tools often lack flexibility. By creating your extension, you gain full control over workflows while learning valuable development skills. Let’s build a tool that connects browser actions to local system tasks.

Building a Browser Automation Extension

Core Files Required

To build your browser extension, you will need a few basic files. These files define your extension’s functionality, appearance, and hidden processes. Below, we will break down the core components and their roles.

Manifest File (manifest.json)

This is the most important file in your extension. Think of it as a map that tells the browser everything it needs to know about your extension – the name, version, permissions, and which files to load.

{

  “manifest_version”: 3,

  “name”: “Automation Execution”,

  “version”: “1.0”,

  “description”: “Run automation from extension”,

  “permissions”: [

    “activeTab”

  ],

  “host_permissions”: [

    “http://localhost:4000/*”

  ],

  “background”: {

    “service_worker”: “background.js”

  },

  “action”: {

    “default_popup”: “popup.html”,

    “default_icon”: “icon.png”

  }

}

Pro Tip: The manifest file defines access scope. For enterprise environments, aligning permission settings with your organization’s security protocols is key to passing compliance checks.

Align Your Extension with Enterprise IT Standards

Partner with AlphaBOLD to ensure your custom browser automation extension meets internal compliance and security requirements before scaling across teams.

Request a Consultation

Popup HTML (popup.html)

This file controls the small pop-up window that opens when you click your extension icon. This HTML file acts as the extension’s interface, allowing you to add interactive elements like buttons or input fields. 

<!DOCTYPE html> 

<html lang=”en”> 

<head> 

    <meta charset=”UTF-8″> 

    <meta name=”viewport” content=”width=device-width, initial-scale=1.0″> 

    <title>Automation Execution</title> 

    <style> 

        body { font-family: Arial, sans-serif; text-align: center; padding: 25px; } 

        #status { margin-top: 11px; font-weight: bold; } 

    </style> 

</head> 

<body> 

    <h2>Run Automation</h2> 

    <button id=”runButton”>Execute Script</button> 

    <p id=”status”>Status: Not started</p> 

    <script src=”popup.js”></script> 

</body> 

</html> 

Button Logic (popup.js)

It adds functionality to your pop-up window. For instance, a button in popup.html requires a script to define its click behavior, such as triggering an action or fetching data.

document.addEventListener(‘DOMContentLoaded’, () => {

    const runButton = document.getElementById(‘runButton’);

    const statusDiv = document.getElementById(‘status’);

    if (!runButton || !statusDiv) {

        console.error(‘❌ Elements missing! Check IDs in HTML.’);

        return;

    }

    runButton.addEventListener(‘click’, async (e) => {

        e.preventDefault();

        runButton.disabled = true;

        statusDiv.textContent = “🔄 Running…”;

        statusDiv.setAttribute(“data-status”, “running”);

        try {

            console.log(“📢 Sending request to automation server…”);

            const response = await fetch(‘http://localhost:4000/run-automation’);

            if (!response.ok) {

                throw new Error(`Server Error: ${response.status} ${response.statusText}`);

            }

            const result = await response.json(); // Expect JSON response result

            console.log(“✅ Server response:”, result);

            if (result.status === “Passed”) {

                statusDiv.textContent = “✅ Script Passed!”;

                statusDiv.setAttribute(“data-status”, “success”);

            } else {

                statusDiv.textContent = “❌ Script Failed!”;

                statusDiv.setAttribute(“data-status”, “error”);

            }

        } catch (error) {

            console.error(‘❌ Fetch Error:’, error);

            statusDiv.textContent = “❌ Failed to run script. Check console.”;

            statusDiv.setAttribute(“data-status”, “error”);

        } finally {

            runButton.disabled = false;

        }

    });

});

Styling (styles.css)

This file controls the look and feel of your pop-up. It changes colors, fonts, and spacing to make things clean and easy to read.

body {

    width: 256px;

    padding: 11px;

    font-family: Arial, sans-serif;

  }

  .container {

    text-align: center;

  }

  #runButton {

    padding: 9px 18px;

    margin: 11px 0;

    cursor: pointer;

  }

  #status {

    margin-top: 10px;

    padding: 8px;

    border-radius: 4px;

    min-height: 40px; /* Ensures space for messages */

    word-wrap: break-word; /* For long output */

  }

  #status[data-status=”running”] {

    background: #e0f0ff;

    color: #004085;

  }

  #status[data-status=”success”] {

    background: #d4edda;

    color: #155724;

  }

  #status[data-status=”error”] {

    background: #f8d7da;

    color: #721c24;

  }

Background Script (background.js)

This file shows nothing on the screen but listens to messages or events. This component enables background automation workflows, executing tasks silently without requiring manual input.

chrome.runtime.onInstalled.addListener(() => {

    console.log(“Automation Runner Extension Installed”);

  });

Load Extension in Browser

  • Open your browser and type this in the address bar: chrome://extensions
  • In the top right corner of the Extensions page, click on the toggle switch labeled Developer Mode.
  • After enabling the Developer Mode, click on the Load Unpacked button.
  • Find the folder where you saved all your files and click Open.
  • You should now see your extension in the list with its name and version.

Automation Framework connection with Extension

Browser extensions cannot directly execute local batch files due to security restrictions. Here is the simplest workaround.

Use Node.js as a Bridge:

  • Create a Node.js server (server.js) to act as a middleman between the extension and your .bat file.
  • The extension sends a request to the Node server, which triggers the batch file.

Create server.js File:

Open the code editor and create a file named server.js. Paste the following code:

const express = require(‘express’) ;

const cors = require(‘cors’) ;

const { exec } = require(‘child_process’) ;

const app = express() ;

const port = 4000 ;

app.use(cors());

app.get(‘/run-automation’, (req, res) => {

    exec(‘”D:\\AlphaBold\\automate_task.bat”‘, (error, stdout, stderr) => {

        if (error) {

            console.error(`Error: ${error.message}`) ;

            return res.status(500).json({ status: “Failed”, message: error.message }) ;

        }

        if (stderr) {

            console.error(`stderr: ${stderr}`) ;

            return res.status(500).json({ status: “Failed”, message: stderr }) ;

        }

        console.log(`stdout: ${stdout}`) ;

        const status = stdout.includes(“Passed”) ? “Passed” : “Failed” ;

        console.log(`Sending response: { status: ${status}, message: ${stdout.trim()} }`) ;

        res.json({ status: status, message: stdout.trim() }) ;

    });

});

app.listen(port, () => {

    console.log(`Automation Execution server running at http://localhost:${port}`) ;

});

Modify the Batch File Path:

Replace ’D:\\AlphaBold\\automate_task.bat’ with the full path to your batch file. Save the file by using double backslashes (\\) for Windows paths.

Server Initiation

  • Navigate to the folder where server.js is saved.
  • Right-click inside the folder, select Open in Terminal (or use CMD/ PowerShell).
  • Run this command to create a package.json file: “npm init -y“
  • The server code uses Express. Install it with: “npm install express“
  • We are ready to start the server with the following command: “node server.js”
  • You will see the Node server running on http://localhost:4000.

Extension Execution

Click the extension icon in your browser. It will send a request to the Node server, which runs the batch file.

Increase Your Team Productivity with Custom Browser Extensions

Let's collaborate to build a secure, scalable browser automation extension around your existing infrastructure.

Request a Consultation

Conclusion

We have now created custom browser extensions and linked them to a batch file using a lightweight Node.js server! This setup opens a world of possibilities for browser-based automation without relying on third-party tools or complex systems. You learned which files make up an extension, how to load it in your browser, and how to bridge the gap between the browser and your local system.

Explore Recent Blog Posts