Cyber Monday is two days away, and most small teams will send more links this week than in any other week of the year: the reminder email, the LinkedIn post, the partner newsletter swap, the last-chance SMS. Every one of those links carries a little label for your analytics, and a surprising number of them will be wrong. Someone types Newsletter, someone else types newsletter, a third person types email, and in January the report shows three sources where there should be one.

I'd build this for the person who sends the links and also has to explain the numbers afterwards: the founder doing their own marketing, the one-person growth team, the agency account manager. Their problem is a habit rather than a missing tool, and a habit gets fixed most easily by making the right version the quickest one to produce.

So this week's build is a small Chrome extension called UTM Tagger. You click it on any page, pick a saved preset or type three values, and it hands you a clean, tagged link on your clipboard. It tidies what you type, warns you when Google Analytics 4 will not recognise your medium, and keeps a history you can export to a spreadsheet. It has no account, no server and no API key, and nothing you type leaves your browser.

What it does, and who it's for

UTM parameters are the five optional tags (utm_source, utm_medium, utm_campaign, utm_content, utm_term) that you add to a link so analytics tools can tell where a visit came from. Google offers a free web form for building them, and plenty of teams keep a shared spreadsheet. Both work, but each one asks you to open a new tab and remember the convention, which is exactly when people cut corners.

The extension removes those steps. When you open it, it reads the address of the page you are on. If that address is already tagged (because you copied it from an old campaign), it strips the old tags from the link and puts them into the form, so you edit rather than start again. As you type, it builds the new link live. When you leave a field it tidies the value to one convention: lowercase, spaces turned into hyphens, accents removed, and anything other than letters, numbers, dots, underscores and hyphens dropped. Black Friday 2026 becomes black-friday-2026, every time, whoever types it.

It also checks one thing most people never think about. GA4 sorts traffic into channels using fixed rules, and a medium of email lands in the Email channel while newsletter matches none of the medium rules, so unless the source gives GA4 another clue, those visits are labelled "Unassigned". The extension shows a warning when your medium is not one of the common values GA4 recognises by default, which is cheaper than discovering it in a quarterly review.

Presets cover the combinations you use every week (weekly newsletter, LinkedIn organic, partner swap). The history tab keeps the last 50 links you copied, newest first, with a "Copy again" button and a CSV export, which also gives you an honest record of what actually went out.

What you need

You need Chrome or another Chromium browser that supports Manifest V3 extensions (Edge and Brave both do). To install it you switch on Developer mode on the extensions page and load the folder; that takes about a minute and is described below. To run the tests you need Node 20 or later and Playwright with its Chromium build. You do not need a Chrome Web Store account, a paid tool or an AI model, because nothing in this app calls one.

How it works

The extension is six small files and an icon folder, and the design rests on one decision: every rule about what a good link looks like lives in a single file of plain functions with no browser code in it. That file, utm.js, can then be tested in Node in milliseconds, and the popup becomes a thin layer that reads the form, calls those functions and writes the result back.

  • manifest.json declares a popup and three permissions: activeTab (read the current tab's address only when you click the icon), storage (presets and history) and clipboardWrite.

  • utm.js holds the rules: normalise, parseUrl, validate, buildTaggedUrl, stripUtm, readUtm and toCsv.

  • store.js wraps Chrome's storage: presets in chrome.storage.sync, so they follow your Chrome profile to another machine, and history in chrome.storage.local, which has far more room.

  • popup.html, popup.css and popup.js are the interface: a Build tab with the form, and a History tab.

The activeTab permission matters more than it looks. An extension that asks to "read and change all your data on all websites" earns a scary install warning and a fair amount of suspicion. With activeTab, the extension sees the address of the current tab only at the moment you click it, and nothing else.

Build it step by step

The build ran in an AI coding agent (Claude) working from a short brief. Nothing was edited by hand afterwards; every change after the first draft came from a failing test, and the three corrections are listed below as prompts you can reuse. The agent started from this brief:

Build a Manifest V3 Chrome extension called UTM Tagger.
- Popup opens on the current tab's URL (activeTab permission only).
- If the URL already has utm_* params, strip them from the link and pre-fill the form.
- Fields: source, medium, campaign (required), content, term (optional).
- Normalise values: lowercase, spaces to hyphens, strip accents, keep a-z 0-9 . _ -
- Keep every other query param and the #fragment untouched.
- Warn when utm_medium is not one GA4's default channel grouping recognises.
- Presets saved by name in chrome.storage.sync; history of the last 50 copied
  links in chrome.storage.local, with Copy again and Export CSV.
- Put all URL logic in a pure module (utm.js) with node:test unit tests.
- Add a Playwright test that loads the unpacked extension and drives the popup
  end to end with example.com links only.
No external services, no API keys, no build step.

The first draft passed most of its tests and failed three, and each failure was a real bug that a user would have hit.

The first came from the unit tests. Given mailto:[email protected], the parser decided the text had no scheme, added https:// to the front and produced a nonsense web address instead of rejecting it. The fix prompt:

parseUrl adds https:// to "mailto:[email protected]" because the scheme check
looks for "://". Treat "word:" as a scheme unless digits follow the colon
(so "localhost:3000" still gets https://), then reject anything not http(s).

The second came from the end-to-end test, and I think it caught the most useful bug of the day. When you typed a messy value and then clicked "Save as preset", nothing happened. Leaving the field tidied the value, which removed a warning line above the buttons, which moved the buttons up, so the click landed on empty space. A person would simply have clicked again and blamed their mouse. The fix prompt:

Clicking Save as preset right after typing does nothing: the blur handler
removes a warning above the buttons, the layout shifts and the click misses.
Move the messages list below the action buttons so nothing above a button
changes height while the user is clicking.

The third came from checking the README against Chrome's documentation. The first draft promised room for "hundreds of presets", but Chrome caps a single storage.sync item at 8 KB, and the whole preset list is stored as one item. At about 153 bytes per typical preset, that is roughly 50. The fix prompt:

The README overstates preset capacity. storage.sync allows 8,192 bytes per
item and presets are one item. Correct the README, catch the quota error in
the Save as preset handler and show it to the user, and add an e2e check that
writing 60 presets is refused.

The code that matters

Three pieces carry the whole app. The first tidies values, and it runs on every value before it goes into a link, so the convention is enforced by the tool rather than by memory:

export function normalise(value) {
  if (value == null) return '';
  return String(value)
    .normalize('NFKD').replace(/[\u0300-\u036f]/g, '') // strip accents: "café" -> "cafe"
    .trim()
    .toLowerCase()
    .replace(/\s+/g, '-')
    .replace(/[^a-z0-9._-]/g, '')
    .replace(/-{2,}/g, '-')
    .replace(/^-+|-+$/g, '');
}

The NFKD step splits an accented letter into the plain letter plus a separate accent mark, and the next line deletes the marks, so café becomes cafe rather than caf. The last two lines collapse repeated hyphens and trim them from the ends, which stops --spring--sale-- from surviving.

The second piece builds the link. It deletes any existing UTM values first, then sets the new ones, and leaves everything else alone:

export function buildTaggedUrl(rawUrl, fields) {
  const url = parseUrl(rawUrl);
  if (!url) throw new Error('Invalid URL');
  for (const key of UTM_KEYS) url.searchParams.delete(key);
  for (const key of UTM_KEYS) {
    const value = normalise(fields[key]);
    if (value) url.searchParams.set(key, value);
  }
  return url.toString();
}

Using the browser's own URL object keeps a ?ref=footer parameter and a #plans fragment exactly where they were. Home-made UTM builders often glue strings together instead, which can put the tags after the #, where analytics tools never see them.

The third piece sits inside validate and checks the medium. It compares the tidied medium against a short list of values that GA4's default channel rules recognise and returns a warning, not an error, because some teams have custom channel groups and know exactly what they are doing:

const medium = normalise(fields.utm_medium);
if (medium && !KNOWN_MEDIUMS.includes(medium)) {
  warnings.push(`"${medium}" is not a medium GA4 groups by default (try one of: ${KNOWN_MEDIUMS.slice(0, 6).join(', ')}).`);
}

Everything else in popup.js is wiring: an input listener that re-runs validation and rebuilds the link on every keystroke, a blur listener that tidies a field when you leave it, and click handlers for copy, presets and export. The full file is at the end of this post.

How it was tested, and what happened

There are two layers of tests. Seven unit tests cover utm.js: tidying messy input, rejecting non-web links, required fields, the warnings, replacing old tags while keeping other parameters and the fragment, stripping and reading tags, and CSV escaping (a URL containing quotes and a comma must still land in one column). All seven pass.

The end-to-end test loads the unpacked extension into Playwright's Chromium and drives the popup the way a person would, with sample data only (example.com links and an invented "Weekly newsletter" preset). It runs nine checks, and all nine pass:

  1. Opening on https://example.com/pricing?ref=footer&utm_source=old-source&utm_medium=email leaves the link as https://example.com/pricing?ref=footer and pre-fills old-source and email.

  2. Typing News Letter, email, Black Friday 2026 and header button produces https://example.com/pricing?ref=footer&utm_source=news-letter&utm_medium=email&utm_campaign=black-friday-2026&utm_content=header-button.

  3. "Save as preset" stores the preset under the name given in the prompt.

  4. "Copy link" writes exactly that link to the clipboard and shows a confirmation.

  5. On a second page the preset fills source, medium and campaign, proving storage survives a reload.

  6. Clearing the campaign disables the copy button and says why; typing newsletter as the medium shows the GA4 warning.

  7. The History tab lists both links, newest first, and the CSV export has a header row and two data rows.

  8. A mailto: link is refused.

  9. Writing 60 presets to sync storage is refused by Chrome with a per-item quota error, which confirms the limit in the README.

One honest note on the clipboard check: Chromium would not grant the test permission to read the clipboard back from an extension page, so the test records every call to navigator.clipboard.writeText and checks the recorded value, while the real write still happens. The test also opens the popup as a normal tab and passes the simulated page address as ?tab=, because a popup opened in a tab would otherwise treat itself as the current page. Both workarounds are commented in the test file.

The screenshots from the run show the Build tab with the tidied fields, the tagged link in a grey box under the form and the orange "Copy link" button, with the warning about the content value just below the buttons; and the History tab with two cards, each showing the time, the source and medium, the full link and a "Copy again" link, above "Export CSV" and "Clear".

Limits, and what could go wrong

It tags links but does not shorten them, so a tagged link is still long. If you post on channels where length matters, you will want a shortener on top.

The tidying rule is opinionated. If your team uses underscores or capitals on purpose, the extension will quietly overrule you until you change normalise(), and an older campaign tagged differently will look like a separate campaign in your reports.

Presets fit in roughly 50 before Chrome's 8 KB per-item limit, as the test above confirmed; saving the next one shows an error rather than failing silently. History stays on one machine, so a colleague will not see your links.

The GA4 list covers the common default rules, not every one. GA4 also uses the source to decide some channels (Paid Search needs a search engine as the source, for instance), and a property with custom channel groups can behave differently, so read the warning as a prompt to check rather than a verdict.

On privacy and cost, the position is simple. The extension makes no network requests, stores everything in your own browser profile and asks for no permission beyond the current tab when clicked. It costs nothing to run. It is not on the Chrome Web Store, and loading an unpacked extension means you are trusting the code you loaded, which is a good reason to read the files below before you do.

Make it yours

The first change I'd make is a shared naming file. Export your team's presets to a small JSON file, keep it somewhere everyone can reach, and add an "Import presets" button that reads it, so a new hire tags links the same way as everyone else from their first day. It is about 30 lines in popup.js and one hidden file input.

A second useful extension is a right-click menu. Add the contextMenus permission and a background service worker, and you can right-click any link on a page (in a draft email, a CMS, a social scheduler) and copy it tagged with your last preset, without opening the popup at all.

A third is a stricter mode for teams. Swap the GA4 warning for an error and restrict source and medium to a fixed list, which is useful when several people tag links and one stray spelling would split a report in two.

[Dev: how does your team name campaigns today? one line, or delete]

Get the code

To install it, save the files below into a folder called extension (keep the names exactly as shown), add three square PNG icons at 16, 48 and 128 pixels in extension/icons/, then open chrome://extensions, switch on Developer mode, click "Load unpacked" and choose the folder. Pin UTM Tagger from the puzzle-piece menu and click it on any page.

To run the tests, put package.json and the tests folder next to extension, then run npm test for the unit tests and node tests/e2e.mjs for the end-to-end test (on a Linux server without a screen, npm run e2e wraps it in xvfb-run).

extension/manifest.json

{
  "manifest_version": 3,
  "name": "UTM Tagger",
  "version": "1.0.0",
  "description": "Tag the current page (or any link) with clean UTM parameters, save presets, and keep a history you can export.",
  "action": {
    "default_popup": "popup.html",
    "default_title": "UTM Tagger"
  },
  "permissions": ["activeTab", "storage", "clipboardWrite"],
  "icons": {
    "16": "icons/icon16.png",
    "48": "icons/icon48.png",
    "128": "icons/icon128.png"
  }
}

extension/utm.js

// utm.js — pure helpers for building and checking UTM-tagged links.
// No browser APIs in here, so the same file runs in the popup and in Node tests.

export const UTM_KEYS = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_content', 'utm_term'];
export const REQUIRED = ['utm_source', 'utm_medium', 'utm_campaign'];

// Turn whatever someone typed into a tidy UTM value:
// "  Spring Sale 2026! " -> "spring-sale-2026"
// Lowercase, spaces and underscores-runs to single hyphens, keeps a-z 0-9 . _ -
export function normalise(value) {
  if (value == null) return '';
  return String(value)
    .normalize('NFKD').replace(/[\u0300-\u036f]/g, '') // strip accents: "café" -> "cafe"
    .trim()
    .toLowerCase()
    .replace(/\s+/g, '-')
    .replace(/[^a-z0-9._-]/g, '')
    .replace(/-{2,}/g, '-')
    .replace(/^-+|-+$/g, '');
}

// Parse a URL the user pasted. Adds https:// when the scheme is missing.
// Returns a URL object, or null when it cannot be a web link.
export function parseUrl(raw) {
  if (!raw || !String(raw).trim()) return null;
  let text = String(raw).trim();
  // Only add https:// when there is no scheme at all. "mailto:x" has a scheme (and is
  // rejected below); "localhost:3000" does not, because a port number follows the colon.
  if (!/^[a-z][a-z0-9+.-]*:(?!\d)/i.test(text)) text = 'https://' + text;
  try {
    const url = new URL(text);
    if (url.protocol !== 'http:' && url.protocol !== 'https:') return null;
    if (!url.hostname.includes('.') && url.hostname !== 'localhost') return null;
    return url;
  } catch {
    return null;
  }
}

// Check the fields before building. Returns a list of problems (empty = fine)
// and a list of softer warnings that do not block the build.
export function validate(fields, rawUrl) {
  const errors = [];
  const warnings = [];
  if (!parseUrl(rawUrl)) errors.push('Enter a valid http(s) link.');
  for (const key of REQUIRED) {
    if (!normalise(fields[key])) errors.push(`${label(key)} is required.`);
  }
  for (const key of UTM_KEYS) {
    const raw = (fields[key] ?? '').trim();
    if (raw && raw !== normalise(raw)) {
      warnings.push(`${label(key)} will be saved as "${normalise(raw)}".`);
    }
  }
  const medium = normalise(fields.utm_medium);
  if (medium && !KNOWN_MEDIUMS.includes(medium)) {
    warnings.push(`"${medium}" is not a medium GA4 groups by default (try one of: ${KNOWN_MEDIUMS.slice(0, 6).join(', ')}).`);
  }
  return { errors, warnings };
}

// Mediums that GA4's default channel grouping recognises without custom rules.
export const KNOWN_MEDIUMS = ['email', 'social', 'cpc', 'paid', 'display', 'affiliate', 'referral', 'organic', 'video', 'sms', 'push', 'audio'];

// Build the tagged link. Existing utm_* parameters are replaced, every other
// query parameter and the #fragment are kept as they were.
export function buildTaggedUrl(rawUrl, fields) {
  const url = parseUrl(rawUrl);
  if (!url) throw new Error('Invalid URL');
  for (const key of UTM_KEYS) url.searchParams.delete(key);
  for (const key of UTM_KEYS) {
    const value = normalise(fields[key]);
    if (value) url.searchParams.set(key, value);
  }
  return url.toString();
}

// Remove every utm_* parameter, e.g. when the current tab is already tagged.
export function stripUtm(rawUrl) {
  const url = parseUrl(rawUrl);
  if (!url) return rawUrl;
  for (const key of [...url.searchParams.keys()]) {
    if (key.toLowerCase().startsWith('utm_')) url.searchParams.delete(key);
  }
  return url.toString();
}

// Read the utm_* values already on a link (used to pre-fill the form).
export function readUtm(rawUrl) {
  const url = parseUrl(rawUrl);
  const out = {};
  if (!url) return out;
  for (const key of UTM_KEYS) {
    const v = url.searchParams.get(key);
    if (v) out[key] = v;
  }
  return out;
}

// History rows -> CSV text, with quotes escaped so commas in URLs are safe.
export function toCsv(rows) {
  const header = ['created_at', 'tagged_url', ...UTM_KEYS];
  const esc = (v) => `"${String(v ?? '').replace(/"/g, '""')}"`;
  const lines = [header.join(',')];
  for (const r of rows) {
    lines.push([r.createdAt, r.url, ...UTM_KEYS.map((k) => r.fields?.[k] ?? '')].map(esc).join(','));
  }
  return lines.join('\n');
}

export function label(key) {
  return { utm_source: 'Source', utm_medium: 'Medium', utm_campaign: 'Campaign', utm_content: 'Content', utm_term: 'Term' }[key] || key;
}

extension/store.js

// store.js — thin wrapper over chrome.storage.
// Presets live in storage.sync (they follow you to other Chrome profiles you sign in to).
// History lives in storage.local (it can grow, and sync has tight size limits).

const HISTORY_LIMIT = 50;

const sync = () => chrome.storage.sync;
const local = () => chrome.storage.local;

export async function getPresets() {
  const { presets = [] } = await sync().get('presets');
  return presets;
}

// Save or overwrite a preset by name (names compare case-insensitively).
export async function savePreset(name, fields) {
  const presets = await getPresets();
  const clean = name.trim();
  const i = presets.findIndex((p) => p.name.toLowerCase() === clean.toLowerCase());
  const preset = { name: clean, fields };
  if (i >= 0) presets[i] = preset; else presets.push(preset);
  presets.sort((a, b) => a.name.localeCompare(b.name));
  await sync().set({ presets });
  return presets;
}

export async function deletePreset(name) {
  const presets = (await getPresets()).filter((p) => p.name !== name);
  await sync().set({ presets });
  return presets;
}

export async function getHistory() {
  const { history = [] } = await local().get('history');
  return history;
}

// Newest first; the same tagged URL is not stored twice in a row.
export async function addHistory(entry) {
  const history = await getHistory();
  if (history[0]?.url !== entry.url) history.unshift(entry);
  const trimmed = history.slice(0, HISTORY_LIMIT);
  await local().set({ history: trimmed });
  return trimmed;
}

export async function clearHistory() {
  await local().set({ history: [] });
}

export async function getLastFields() {
  const { lastFields = null } = await local().get('lastFields');
  return lastFields;
}

export async function setLastFields(fields) {
  await local().set({ lastFields: fields });
}

extension/popup.html

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>UTM Tagger</title>
  <link rel="stylesheet" href="popup.css">
</head>
<body>
  <header>
    <h1>UTM Tagger</h1>
    <nav>
      <button class="tab active" data-view="build" type="button">Build</button>
      <button class="tab" data-view="history" type="button">History</button>
    </nav>
  </header>

  <main id="view-build">
    <label class="field">
      <span>Link</span>
      <input id="url" type="url" placeholder="https://example.com/pricing" autocomplete="off">
    </label>

    <div class="preset-row">
      <select id="preset" aria-label="Preset">
        <option value="">Choose a preset…</option>
      </select>
      <button id="delete-preset" type="button" class="ghost" title="Delete preset" disabled>Delete</button>
    </div>

    <div class="grid">
      <label class="field"><span>Source *</span><input id="utm_source" list="sources" placeholder="newsletter"></label>
      <label class="field"><span>Medium *</span><input id="utm_medium" list="mediums" placeholder="email"></label>
      <label class="field wide"><span>Campaign *</span><input id="utm_campaign" placeholder="black-friday-2026"></label>
      <label class="field"><span>Content</span><input id="utm_content" placeholder="header-button"></label>
      <label class="field"><span>Term</span><input id="utm_term" placeholder="optional"></label>
    </div>

    <datalist id="sources">
      <option value="newsletter"><option value="linkedin"><option value="x"><option value="google"><option value="facebook"><option value="partner">
    </datalist>
    <datalist id="mediums"></datalist>

    <div class="output">
      <textarea id="result" readonly rows="3" placeholder="Your tagged link appears here"></textarea>
      <div class="actions">
        <button id="copy" type="button" class="primary" disabled>Copy link</button>
        <button id="save-preset" type="button" class="ghost">Save as preset</button>
      </div>
    </div>
    <!-- Messages sit below the buttons so they never push a button out from under the cursor. -->
    <ul id="messages" aria-live="polite"></ul>
    <p id="toast" role="status"></p>
  </main>

  <main id="view-history" hidden>
    <ol id="history-list"></ol>
    <p id="history-empty">No links yet. Copy one from the Build tab and it will appear here.</p>
    <div class="actions">
      <button id="export" type="button" class="primary">Export CSV</button>
      <button id="clear" type="button" class="ghost">Clear</button>
    </div>
  </main>

  <script type="module" src="popup.js"></script>
</body>
</html>

extension/popup.css

:root {
  --ink: #111111;
  --muted: #5b5b5b;
  --line: #e3e3e3;
  --bg: #ffffff;
  --soft: #f6f6f4;
  --accent: #f97316;
  --accent-ink: #c2410c;
  --error: #b42318;
  --warn: #8a5a00;
  font-family: Inter, system-ui, -apple-system, "Segoe UI", sans-serif;
}
* { box-sizing: border-box; }
body { margin: 0; width: 380px; background: var(--bg); color: var(--ink); font-size: 13px; }
header { display: flex; align-items: center; justify-content: space-between; padding: 12px 14px; border-bottom: 1px solid var(--line); }
h1 { font-size: 15px; margin: 0; letter-spacing: -0.01em; }
nav { display: flex; gap: 4px; }
.tab { border: 0; background: transparent; padding: 6px 10px; border-radius: 6px; cursor: pointer; color: var(--muted); font: inherit; }
.tab.active { background: var(--soft); color: var(--ink); font-weight: 600; }
main { padding: 12px 14px 14px; }
.field { display: flex; flex-direction: column; gap: 4px; margin-bottom: 10px; }
.field span { font-size: 11px; color: var(--muted); text-transform: uppercase; letter-spacing: 0.04em; }
input, select, textarea { font: inherit; padding: 8px 9px; border: 1px solid var(--line); border-radius: 6px; background: #fff; color: var(--ink); width: 100%; }
input:focus, select:focus, textarea:focus { outline: 2px solid var(--accent); outline-offset: -1px; }
.grid { display: grid; grid-template-columns: 1fr 1fr; column-gap: 10px; }
.grid .wide { grid-column: 1 / -1; }
.preset-row { display: flex; gap: 8px; margin-bottom: 10px; }
textarea { resize: none; background: var(--soft); word-break: break-all; }
.actions { display: flex; gap: 8px; margin-top: 8px; }
button.primary, button.ghost { font: inherit; border-radius: 6px; padding: 8px 12px; cursor: pointer; }
button.primary { background: var(--accent); color: #fff; border: 0; font-weight: 600; }
button.primary:disabled { opacity: 0.45; cursor: not-allowed; }
button.ghost { background: transparent; border: 1px solid var(--line); color: var(--ink); }
button.ghost:disabled { opacity: 0.45; }
#messages { list-style: none; padding: 0; margin: 8px 0 0; }
#messages li { font-size: 12px; padding: 2px 0; }
#messages li.error { color: var(--error); }
#messages li.warn { color: var(--warn); }
#toast { min-height: 16px; margin: 8px 0 0; color: var(--accent-ink); font-size: 12px; }
#history-list { list-style: none; padding: 0; margin: 0; max-height: 360px; overflow: auto; }
#history-list li { border: 1px solid var(--line); border-radius: 6px; padding: 8px; margin-bottom: 8px; }
#history-list .meta { color: var(--muted); font-size: 11px; margin-bottom: 4px; }
#history-list .link { word-break: break-all; }
#history-list button { margin-top: 6px; font: inherit; font-size: 12px; background: none; border: 0; color: var(--accent-ink); cursor: pointer; padding: 0; }
#history-empty { color: var(--muted); }

extension/popup.js

// popup.js — wires the form to the pure helpers in utm.js and to storage in store.js.
import { UTM_KEYS, KNOWN_MEDIUMS, normalise, validate, buildTaggedUrl, stripUtm, readUtm, toCsv } from './utm.js';
import * as store from './store.js';

const $ = (id) => document.getElementById(id);
const els = {
  url: $('url'), preset: $('preset'), deletePreset: $('delete-preset'),
  result: $('result'), copy: $('copy'), savePreset: $('save-preset'),
  messages: $('messages'), toast: $('toast'),
  historyList: $('history-list'), historyEmpty: $('history-empty'),
  exportBtn: $('export'), clear: $('clear'),
};
const inputs = Object.fromEntries(UTM_KEYS.map((k) => [k, $(k)]));

// Fill the medium suggestions from the list GA4 recognises.
$('mediums').innerHTML = KNOWN_MEDIUMS.map((m) => `<option value="${m}">`).join('');

function readFields() {
  return Object.fromEntries(UTM_KEYS.map((k) => [k, inputs[k].value]));
}

function writeFields(fields = {}) {
  for (const k of UTM_KEYS) inputs[k].value = fields[k] ?? '';
}

// Re-run on every keystroke: validate, show messages, build the link.
function refresh() {
  const fields = readFields();
  const { errors, warnings } = validate(fields, els.url.value);
  els.messages.innerHTML = '';
  const show = (text, cls) => {
    const li = document.createElement('li');
    li.className = cls; li.textContent = text; els.messages.append(li);
  };
  // Only show "required" errors once the user has started typing in the form.
  const touched = UTM_KEYS.some((k) => inputs[k].value.trim()) || els.url.value.trim();
  if (touched) errors.forEach((e) => show(e, 'error'));
  warnings.forEach((w) => show(w, 'warn'));

  if (errors.length) {
    els.result.value = '';
    els.copy.disabled = true;
  } else {
    els.result.value = buildTaggedUrl(els.url.value, fields);
    els.copy.disabled = false;
  }
  store.setLastFields(fields);
}

function toast(text) {
  els.toast.textContent = text;
  clearTimeout(toast.t);
  toast.t = setTimeout(() => (els.toast.textContent = ''), 2500);
}

async function renderPresets(selected = '') {
  const presets = await store.getPresets();
  els.preset.innerHTML = '<option value="">Choose a preset…</option>' +
    presets.map((p) => `<option value="${escapeHtml(p.name)}">${escapeHtml(p.name)}</option>`).join('');
  els.preset.value = selected;
  els.deletePreset.disabled = !selected;
  return presets;
}

async function renderHistory() {
  const history = await store.getHistory();
  els.historyList.innerHTML = '';
  els.historyEmpty.hidden = history.length > 0;
  els.exportBtn.disabled = history.length === 0;
  for (const h of history) {
    const li = document.createElement('li');
    const when = new Date(h.createdAt).toLocaleString();
    li.innerHTML = `<div class="meta">${escapeHtml(when)} · ${escapeHtml(h.fields.utm_source)} / ${escapeHtml(h.fields.utm_medium)}</div>
      <div class="link"></div><button type="button">Copy again</button>`;
    li.querySelector('.link').textContent = h.url;
    li.querySelector('button').addEventListener('click', async () => {
      await navigator.clipboard.writeText(h.url);
      li.querySelector('button').textContent = 'Copied';
    });
    els.historyList.append(li);
  }
}

function escapeHtml(s) {
  return String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
}

// Work out which link to start from. Normally the active tab; tests can pass ?tab=<url>
// because when the popup is opened as a normal page the "active tab" is the popup itself.
async function startingUrl() {
  const override = new URLSearchParams(location.search).get('tab');
  if (override) return override;
  try {
    const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
    return tab?.url && /^https?:/.test(tab.url) ? tab.url : '';
  } catch {
    return '';
  }
}

async function init() {
  const tabUrl = await startingUrl();
  const existing = readUtm(tabUrl);
  els.url.value = tabUrl ? stripUtm(tabUrl) : '';
  // If the page is already tagged, show its tags; otherwise reuse what was typed last time.
  writeFields(Object.keys(existing).length ? existing : (await store.getLastFields()) ?? {});
  await renderPresets();
  refresh();
}

// --- events ---
[els.url, ...Object.values(inputs)].forEach((el) => el.addEventListener('input', refresh));

// Tidy a value when the user leaves the field, so they see what will be saved.
Object.values(inputs).forEach((el) => el.addEventListener('blur', () => {
  const n = normalise(el.value);
  if (n !== el.value) { el.value = n; refresh(); }
}));

els.preset.addEventListener('change', async () => {
  const name = els.preset.value;
  els.deletePreset.disabled = !name;
  if (!name) return;
  const preset = (await store.getPresets()).find((p) => p.name === name);
  if (preset) {
    // A preset fills source/medium/campaign etc. but keeps blanks blank, so
    // per-link fields like content can be added afterwards.
    writeFields(preset.fields);
    refresh();
    toast(`Applied "${name}"`);
  }
});

els.savePreset.addEventListener('click', async () => {
  const fields = Object.fromEntries(UTM_KEYS.map((k) => [k, normalise(inputs[k].value)]));
  if (!fields.utm_source || !fields.utm_medium) { toast('Fill in source and medium first'); return; }
  const suggested = [fields.utm_source, fields.utm_medium, fields.utm_campaign].filter(Boolean).join(' / ');
  const name = prompt('Name this preset', suggested);
  if (!name || !name.trim()) return;
  try {
    await store.savePreset(name, fields);
  } catch (err) {
    // storage.sync caps one item at 8 KB; the whole preset list is one item.
    toast('Could not save: ' + (err?.message || 'storage limit reached'));
    return;
  }
  await renderPresets(name.trim());
  toast(`Saved preset "${name.trim()}"`);
});

els.deletePreset.addEventListener('click', async () => {
  const name = els.preset.value;
  if (!name || !confirm(`Delete preset "${name}"?`)) return;
  await store.deletePreset(name);
  await renderPresets();
  toast('Preset deleted');
});

els.copy.addEventListener('click', async () => {
  const url = els.result.value;
  if (!url) return;
  await navigator.clipboard.writeText(url);
  const fields = Object.fromEntries(UTM_KEYS.map((k) => [k, normalise(inputs[k].value)]));
  await store.addHistory({ url, fields, createdAt: new Date().toISOString() });
  toast('Copied to clipboard');
});

document.querySelectorAll('.tab').forEach((btn) => btn.addEventListener('click', async () => {
  document.querySelectorAll('.tab').forEach((b) => b.classList.toggle('active', b === btn));
  const view = btn.dataset.view;
  $('view-build').hidden = view !== 'build';
  $('view-history').hidden = view !== 'history';
  if (view === 'history') await renderHistory();
}));

els.exportBtn.addEventListener('click', async () => {
  const csv = toCsv(await store.getHistory());
  const blob = new Blob([csv], { type: 'text/csv' });
  const a = document.createElement('a');
  a.href = URL.createObjectURL(blob);
  a.download = `utm-links-${new Date().toISOString().slice(0, 10)}.csv`;
  a.click();
  setTimeout(() => URL.revokeObjectURL(a.href), 1000);
});

els.clear.addEventListener('click', async () => {
  if (!confirm('Clear all saved links?')) return;
  await store.clearHistory();
  await renderHistory();
});

init();

package.json

{
  "name": "utm-tagger",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "scripts": {
    "test": "node --test tests/utm.test.mjs",
    "e2e": "xvfb-run -a node tests/e2e.mjs"
  }
}

tests/utm.test.mjs

// Unit tests for the pure helpers. Run with: node --test tests/
import test from 'node:test';
import assert from 'node:assert/strict';
import { normalise, parseUrl, validate, buildTaggedUrl, stripUtm, readUtm, toCsv } from '../extension/utm.js';

test('normalise tidies messy input', () => {
  assert.equal(normalise('  Spring Sale 2026! '), 'spring-sale-2026');
  assert.equal(normalise('LinkedIn'), 'linkedin');
  assert.equal(normalise('Café  Promo'), 'cafe-promo');
  assert.equal(normalise('--a---b--'), 'a-b');
  assert.equal(normalise(undefined), '');
});

test('parseUrl adds https and rejects non-web links', () => {
  assert.equal(parseUrl('example.com/pricing').href, 'https://example.com/pricing');
  assert.equal(parseUrl('mailto:[email protected]'), null);
  assert.equal(parseUrl('not a url'), null);
  assert.equal(parseUrl(''), null);
});

test('validate requires source, medium, campaign and a link', () => {
  const { errors } = validate({}, '');
  assert.equal(errors.length, 4);
  const ok = validate({ utm_source: 'newsletter', utm_medium: 'email', utm_campaign: 'launch' }, 'https://example.com');
  assert.deepEqual(ok.errors, []);
  assert.deepEqual(ok.warnings, []);
});

test('validate warns on values that will change and unknown mediums', () => {
  const { errors, warnings } = validate({ utm_source: 'News Letter', utm_medium: 'newsletter', utm_campaign: 'x' }, 'example.com');
  assert.deepEqual(errors, []);
  assert.ok(warnings.some((w) => w.includes('"news-letter"')));
  assert.ok(warnings.some((w) => w.includes('not a medium GA4')));
});

test('buildTaggedUrl replaces old utm tags but keeps other params and the fragment', () => {
  const out = buildTaggedUrl('https://example.com/p?ref=abc&utm_source=old#plans', {
    utm_source: 'LinkedIn', utm_medium: 'social', utm_campaign: 'Black Friday', utm_content: '',
  });
  const url = new URL(out);
  assert.equal(url.searchParams.get('ref'), 'abc');
  assert.equal(url.searchParams.get('utm_source'), 'linkedin');
  assert.equal(url.searchParams.get('utm_campaign'), 'black-friday');
  assert.equal(url.searchParams.has('utm_content'), false);
  assert.equal(url.hash, '#plans');
  assert.equal(out, 'https://example.com/p?ref=abc&utm_source=linkedin&utm_medium=social&utm_campaign=black-friday#plans');
});

test('stripUtm and readUtm round-trip', () => {
  const tagged = 'https://example.com/?a=1&utm_source=x&utm_medium=email&UTM_Campaign=y';
  assert.equal(stripUtm(tagged), 'https://example.com/?a=1');
  assert.deepEqual(readUtm(tagged), { utm_source: 'x', utm_medium: 'email' });
});

test('toCsv escapes quotes and keeps column order', () => {
  const csv = toCsv([{ createdAt: '2026-11-27T00:00:00.000Z', url: 'https://example.com/?q="a,b"', fields: { utm_source: 's', utm_medium: 'email', utm_campaign: 'c' } }]);
  const [header, row] = csv.split('\n');
  assert.equal(header, 'created_at,tagged_url,utm_source,utm_medium,utm_campaign,utm_content,utm_term');
  assert.equal(row, '"2026-11-27T00:00:00.000Z","https://example.com/?q=""a,b""","s","email","c","",""');
});

tests/e2e.mjs

// End-to-end test: loads the unpacked extension into Chromium and drives the popup.
// Run with: npm run e2e   (needs a display; xvfb-run provides one on Linux servers)
// All data here is made up: example.com links and sample campaign names.
import { createRequire } from 'node:module';
import { createHash } from 'node:crypto';
import { mkdtempSync, mkdirSync, readFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import assert from 'node:assert/strict';

// require() so a globally installed Playwright is found too (ESM imports ignore NODE_PATH).
const { chromium } = createRequire(import.meta.url)('playwright');

const here = path.dirname(fileURLToPath(import.meta.url));
const extPath = path.resolve(here, '../extension');
const shots = path.resolve(here, '../shots');
mkdirSync(shots, { recursive: true });

// Chrome derives an unpacked extension's ID from its folder path:
// sha256(path), first 32 hex digits, each digit 0-f mapped to a-p.
const extId = createHash('sha256').update(extPath).digest('hex').slice(0, 32)
  .replace(/[0-9a-f]/g, (c) => String.fromCharCode(97 + parseInt(c, 16)));

const context = await chromium.launchPersistentContext(mkdtempSync(path.join(tmpdir(), 'utm-')), {
  headless: false,
  viewport: { width: 380, height: 560 },
  deviceScaleFactor: 2,
  acceptDownloads: true,
  args: [`--disable-extensions-except=${extPath}`, `--load-extension=${extPath}`],
});
// Record every clipboard write so the test can check what was copied. The real
// writeText still runs; Chromium will not grant clipboard-read to extension origins here.
await context.addInitScript(() => {
  const real = navigator.clipboard.writeText.bind(navigator.clipboard);
  window.__copied = [];
  navigator.clipboard.writeText = async (t) => { window.__copied.push(t); return real(t); };
});

const popup = (tabUrl) => `chrome-extension://${extId}/popup.html?tab=${encodeURIComponent(tabUrl)}`;
const page = await context.newPage();
const log = (m) => console.log('✓', m);
// Answer the popup's prompt()/confirm() dialogs the way a user would.
page.on('dialog', (d) => d.accept(d.type() === 'prompt' ? 'Weekly newsletter' : undefined));
page.on('pageerror', (e) => console.log('PAGE ERROR', e.message));
page.on('console', (m) => m.type() === 'error' && console.log('CONSOLE', m.text()));

// 1. A page that is already tagged: the link is cleaned and the old tags pre-fill the form.
await page.goto(popup('https://example.com/pricing?ref=footer&utm_source=old-source&utm_medium=email'));
assert.equal(await page.inputValue('#url'), 'https://example.com/pricing?ref=footer');
assert.equal(await page.inputValue('#utm_source'), 'old-source');
log('existing UTM tags stripped from link and pre-filled');

// 2. Type messy values; the link updates as you type and the warnings explain the changes.
await page.fill('#utm_source', 'News Letter');
await page.fill('#utm_medium', 'email');
await page.fill('#utm_campaign', 'Black Friday 2026');
await page.fill('#utm_content', 'header button');
const expected = 'https://example.com/pricing?ref=footer&utm_source=news-letter&utm_medium=email&utm_campaign=black-friday-2026&utm_content=header-button';
assert.equal(await page.inputValue('#result'), expected);
// Fields already left are tidied on blur; the one still focused shows a warning instead.
assert.equal(await page.inputValue('#utm_campaign'), 'black-friday-2026');
assert.match(await page.textContent('#messages'), /Content will be saved as "header-button"/);
await page.screenshot({ path: `${shots}/1-build-warnings.png` });
log('tagged link built and normalised: ' + expected);

// 3. Save as preset (the name prompt is answered by the test).
await page.click('#save-preset');
await page.waitForSelector('#preset option[value="Weekly newsletter"]', { state: 'attached' });
log('preset saved');

// 4. Copy: clipboard holds the link and it goes into history.
await page.click('#copy');
assert.equal(await page.evaluate(() => window.__copied.at(-1)), expected);
await page.waitForFunction(() => document.querySelector('#toast').textContent.includes('Copied'));
await page.screenshot({ path: `${shots}/2-copied.png` });
log('copied to clipboard');

// 5. New page, apply the preset, add a per-link content value, copy again.
await page.goto(popup('https://example.com/blog/holiday-checklist'));
await page.selectOption('#preset', 'Weekly newsletter');
assert.equal(await page.inputValue('#utm_campaign'), 'black-friday-2026');
await page.fill('#utm_content', 'footer-link');
const second = await page.inputValue('#result');
assert.equal(second, 'https://example.com/blog/holiday-checklist?utm_source=news-letter&utm_medium=email&utm_campaign=black-friday-2026&utm_content=footer-link');
await page.click('#copy');
await page.waitForFunction(() => document.querySelector('#toast').textContent.includes('Copied'));
log('preset applied after reload (storage persisted)');

// 6. Missing campaign blocks the copy button and says why.
await page.fill('#utm_campaign', '');
assert.equal(await page.isDisabled('#copy'), true);
assert.match(await page.textContent('#messages'), /Campaign is required/);
await page.fill('#utm_medium', 'newsletter');
assert.match(await page.textContent('#messages'), /not a medium GA4 groups by default/);
await page.screenshot({ path: `${shots}/3-errors.png` });
log('required-field error and GA4 medium warning shown');

// 7. History tab lists both links, newest first, and exports a CSV.
await page.click('.tab[data-view="history"]');
const items = await page.locator('#history-list li .link').allTextContents();
assert.deepEqual(items, [second, expected]);
await page.screenshot({ path: `${shots}/4-history.png` });
const [download] = await Promise.all([page.waitForEvent('download'), page.click('#export')]);
const csv = readFileSync(await download.path(), 'utf8').split('\n');
assert.equal(csv.length, 3);
assert.ok(csv[1].includes('footer-link'));
log('history shows 2 links; CSV export has header + 2 rows (' + download.suggestedFilename() + ')');

// 8. Non-web links are refused.
await page.goto(popup('mailto:[email protected]'));
await page.fill('#url', 'mailto:[email protected]');
await page.fill('#utm_source', 'x');
assert.equal(await page.isDisabled('#copy'), true);
assert.match(await page.textContent('#messages'), /valid http/);
log('mailto: link rejected');

// 9. The 8 KB per-item cap on storage.sync is real: 60 typical presets in one item are refused.
const capError = await page.evaluate(async () => {
  const presets = Array.from({ length: 60 }, (_, i) => ({ name: `Preset number ${i}`, fields: { utm_source: 'news-letter', utm_medium: 'email', utm_campaign: 'black-friday-2026', utm_content: '', utm_term: '' } }));
  try { await chrome.storage.sync.set({ presets }); return null; } catch (e) { return e.message; }
});
assert.ok(capError && /QuotaBytesPerItem|QUOTA_BYTES_PER_ITEM/i.test(capError), 'expected a per-item quota error, got: ' + capError);
log('storage.sync refuses an oversized preset list: ' + capError);

await context.close();
console.log('\nAll end-to-end checks passed.');

Sources