Chapter 7

Helper Functions

Before we start building the actual scraping functionality, we need a few helper components that connect the different parts of our extension. These files do not scrape data themselves. Instead, they provide the configuration, interface, styling, and communication mechanisms that the scraper will use.

The Manifest

We have already seen manifest.json, but it is worth looking at it again now that the project has more structure. The manifest tells Chrome how to load our extension and which pages our scripts are allowed to operate on.

{
    "manifest_version": 3,
    "name": "Web Scraper",
    "version": "1.0",
    "permissions": [
        "storage",
        "tabs"
    ],
    "action": {
        "default_popup": "menu.html"
    },
    "host_permissions": [
        "<all_urls>"
    ],
    "content_scripts": [
        {
            "matches": ["<all_urls>"],
            "js": [
                "scraper.js",
                "ui.js"
            ],
            "run_at": "document_idle"
        }
    ]
}

The important change compared with the earlier template is that we now use <all_urls>. This allows our extension to operate on any website. That is useful for a general-purpose scraper because we do not want to modify the extension manifest every time we want to scrape a different website.

The manifest also tells Chrome to load scraper.js and ui.js into matching pages after the page has loaded. The popup itself is menu.html, which will be opened when the user clicks the extension icon.

The Menu

menu.html defines the interface that appears when we open the extension popup. We divide the controls into three sections: scraper management, selectors, and storage.

<html>
    <head>
        <link rel="stylesheet" href="menu.css">
    </head>
    <body>
        <div class="section">
            <div class="section-title">Scraper</div>
            <div class="button-row">
                <button id="create">Create Scraper</button>
                <button id="remove">Remove Scraper</button>
            </div>
            <div class="button-row">
                <button id="load">Load Scraper</button>
                <button id="save">Save Scraper</button>
                <input type="file" id="file" hidden>
            </div>
            <div class="button-row">
                <button id="start">Start Scraper</button>
                <button id="stop">Stop Scraper</button>
            </div>
        </div>
        <div class="section">
            <div class="section-title">Selectors</div>
            <div class="button-row">
                <button id="links">Set Listings</button>
                <button id="pagination">Set Pagination</button>
            </div>
            <div class="button-row">
                <button id="select">Select Element</button>
                <button id="deselect">Remove Element</button>
            </div>
            <div class="button-row">
                <button id="done">Done Selecting</button>
                <button id="preview">Preview Data</button>
            </div>
        </div>
        <div class="section">
            <div class="section-title">Storage</div>
            <div class="button-row">
                <button id="download">Download Data</button>
                <button id="clear">Clear Data</button>
            </div>
        </div>
        <script src="menu.js"></script>
    </body>
</html>

The buttons are deliberately given meaningful IDs such as create, start, links, and download. These IDs will later become the connection between the visible button and the action that should be performed.

Notice that the HTML itself contains very little application logic. It describes what the user can do, while menu.js will handle what happens when a button is clicked.

The Menu Styling

menu.css controls the appearance of the popup. There is nothing particularly scraper-specific here; its job is simply to make the controls compact and readable.

* {
    box-sizing: border-box;
}

html {
    width: 400px;
    margin: 0;
    overflow: auto;
}

body {
    padding: 12px;
    background: #f5f5f7;
    color: #222;
    font-family: Arial, sans-serif;
}

.section {
    margin-top: 12px;
}

.section-title {
    margin-bottom: 6px;
    font-size: 11px;
    font-weight: bold;
    color: #888;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

.button-row {
    margin: 0px;
    padding: 0px;
    display: flex;
    flex-direction: row;
    gap: 6px;
}

button, a.button {
    display: block;
    width: 100%;
    margin-top: 6px;
    padding: 9px 12px;
    border: 1px solid #d0d0d0;
    border-radius: 6px;
    background: white;
    color: #222;
    font-family: Arial, sans-serif;
    font-size: 13px;
    line-height: normal;
    text-align: center;
    text-decoration: none;
    cursor: pointer;
}

button:hover, a.button:hover {
    background: #eeeeee;
    border-color: #bbb;
}

button:active, a.button:active {
    background: #e2e2e2;
}

The important thing to understand is the separation of responsibilities. menu.html describes the interface, while menu.css determines how that interface looks. Neither file needs to know anything about how scraping works.

Communicating With the Target Page

This leaves us with menu.js. The popup runs in its own extension context, while scraper.js and ui.js run inside the target web page. They are separate environments, so the popup cannot simply call functions defined by the scripts on the page.

Our solution is to send messages to the active tab. The message contains an action value, and the scripts running on the target page can respond to that action.

const fileInput = document.getElementById("file");

document.getElementById("load").onclick = () => {
    fileInput.click();
};

fileInput.onchange = async () => {
    const file = fileInput.files[0];
    if (!file) return;
    const [tab] = await chrome.tabs.query({
        active: true,
        currentWindow: true
    }); chrome.tabs.sendMessage(tab.id, { action: await file.text() });
};

for (let btn of document.getElementsByTagName("button")) {
    if (btn.id == "load") continue;
    let action = btn.id;
    document.getElementById(action).onclick = async () => {
        const [tab] = await chrome.tabs.query({
            active: true,
            currentWindow: true
        }); chrome.tabs.sendMessage(tab.id, { action: action });
    };
}

The first part handles the hidden file input used by the Load Scraper button. Clicking the button programmatically opens the browser's file picker. Once a file is selected, its contents are read and sent to the active tab.

The more interesting part is the loop at the end. Instead of writing a separate click handler for every button, we loop through all buttons and use each button's ID as the action name.

For example, clicking the button with id="start" results in a message containing { action: "start" }. Clicking id="links" produces { action: "links" }. The same mechanism works for all of the other buttons.

We first find the active browser tab with chrome.tabs.query() and then send the message to that tab using chrome.tabs.sendMessage(). The scripts running on the target page can listen for these messages and decide what to do with them.

A Simple Communication Model

At this point, we can think of the extension as having two sides. The popup is where the user clicks buttons, while the target page is where the actual scraper operates.

menu.html, menu.css, and menu.js form the popup side. The manifest loads scraper.js and ui.js into the target page. menu.js then acts as the communication bridge between the two.

A Useful Pattern

The button ID becomes the message action. This gives us a simple convention: the popup does not need to know how an operation works; it only needs to tell the page which operation the user requested. The page-side scripts can then implement that operation.

These helper files give us the foundation for the rest of the project. The interface exists, the popup can communicate with the active page, and Chrome knows which scripts to inject. We can now move on to the code that actually makes the scraper configurable and usable.