DEV Community

Fernando Paladini
Fernando Paladini

Posted on

Migrate a Cookie-Scoped Chrome Extension to Manifest V3 and Verify It with Node.js

Small browser extensions that read and write cookies often break in three places at once during a Manifest V3 migration: host patterns move out of permissions, background scripts become ephemeral service workers without DOM globals like alert(), and options-page messaging requires explicit asynchronous response handling.

paladini/Youtube-Transparent-Player is a compact, MIT-licensed Chrome extension originally written in 2015 for Manifest V2 and migrated to Manifest V3 in release v0.4.0. Because the entire extension consists of manifest.json, options.html, js/background.js, and js/options.js with zero npm dependencies or build steps, it serves as a clear, inspectable specimen of a real MV2-to-MV3 port.

Set one expectation upfront: YouTube retired the 2015 VISITOR_INFO1_LIVE=Q06SngRDTGA player experiment years ago, so loading v0.4.0 today will not bring back YouTube's old transparent control bar. Its practical value today is architectural: studying how a cookie-scoped extension adapts to Manifest V3 and verifying its service worker locally in Node.js before touching any browser profile.

TL;DR

Download the v0.4.0 release archive (YoutubeTransparentPlayer-mv3.zip), inspect how manifest.json and js/background.js separate cookie permissions, lifecycle hooks, and options messaging, and run a built-in Node.js node:vm harness to verify both happy-path cookie writes and a legacy PREF string-slicing edge case without opening Chrome.

Prerequisites

  • Node.js 18 or newer (uses only built-in node:fs, node:path, node:vm, and node:assert/strict; verified on Node.js 24).
  • curl and unzip (or PowerShell Invoke-WebRequest and Expand-Archive on Windows) to download and unpack the v0.4.0 release archive.
  • Optional: Chromium or Google Chrome launched with a disposable --user-data-dir if you also want to inspect the unpacked folder in chrome://extensions.

Minimal Working Path

The repository has one tagged GitHub release, v0.4.0 (commit 1865c5e), while master (557d42f) is one README.md-only commit ahead and leaves every file under src/ unchanged. Pin v0.4.0 directly so your local check matches the published MV3 release asset.

Create a clean directory and unpack YoutubeTransparentPlayer-mv3.zip:

mkdir ytp-mv3-check && cd ytp-mv3-check
curl -fLO https://github.com/paladini/Youtube-Transparent-Player/releases/download/v0.4.0/YoutubeTransparentPlayer-mv3.zip
unzip -q YoutubeTransparentPlayer-mv3.zip -d unpacked
Enter fullscreen mode Exit fullscreen mode

Save the following verification script as verify-mv3.cjs next to unpacked/. It checks the Manifest V3 fields and executes unpacked/js/background.js inside an isolated node:vm context against an in-memory chrome.cookies and chrome.runtime stub:

const fs = require("node:fs");
const path = require("node:path");
const vm = require("node:vm");
const assert = require("node:assert/strict");

const extDir = path.join(__dirname, "unpacked");
const manifest = JSON.parse(fs.readFileSync(path.join(extDir, "manifest.json"), "utf8"));

assert.equal(manifest.manifest_version, 3);
assert.equal(manifest.version, "0.4.0");
assert.deepEqual(manifest.permissions, ["cookies"]);
assert.deepEqual(manifest.host_permissions, ["*://*.youtube.com/*"]);

for (const rel of [
  manifest.background.service_worker,
  manifest.options_ui.page,
  ...Object.values(manifest.icons),
]) {
  assert.equal(fs.existsSync(path.join(extDir, rel)), true, `Missing asset: ${rel}`);
}

function bootWorker(initialCookies) {
  const jar = new Map(Object.entries(initialCookies));
  const listeners = { onInstalled: [], onStartup: [], onMessage: [] };
  const chrome = {
    cookies: {
      get({ name }, cb) {
        setImmediate(() => cb(jar.has(name) ? { name, value: jar.get(name) } : null));
      },
      set(details, cb) {
        jar.set(details.name, details.value);
        setImmediate(() => cb && cb(details));
      },
    },
    runtime: {
      onInstalled: { addListener: (fn) => listeners.onInstalled.push(fn) },
      onStartup: { addListener: (fn) => listeners.onStartup.push(fn) },
      onMessage: { addListener: (fn) => listeners.onMessage.push(fn) },
    },
  };
  const source = fs.readFileSync(path.join(extDir, manifest.background.service_worker), "utf8");
  vm.runInNewContext(source, { chrome, Date });
  return { jar, listeners };
}

(async () => {
  const fresh = bootWorker({});
  fresh.listeners.onInstalled[0]();
  await new Promise((r) => setTimeout(r, 30));
  console.log("1. Fresh install cookies:", Object.fromEntries(fresh.jar));

  const existing = bootWorker({ PREF: "f6=400&hl=pt&gl=BR" });
  const reply = await new Promise((resolve) => {
    assert.equal(existing.listeners.onMessage[0]({ type: "reinstall" }, {}, resolve), true);
  });
  console.log("2. Options reinstall:", { reply, cookies: Object.fromEntries(existing.jar) });

  const noLang = bootWorker({ PREF: "f6=40000080" });
  await new Promise((resolve) => noLang.listeners.onMessage[0]({ type: "reinstall" }, {}, resolve));
  console.log("3. PREF without hl=:", Object.fromEntries(noLang.jar));
})();
Enter fullscreen mode Exit fullscreen mode

Run the harness:

node verify-mv3.cjs
Enter fullscreen mode Exit fullscreen mode

Expected Result and Reproducible Verification

Running node verify-mv3.cjs exits with code 0 and prints:

1. Fresh install cookies: { PREF: 'hl=en', VISITOR_INFO1_LIVE: 'Q06SngRDTGA' }
2. Options reinstall: {
  reply: {
    success: true,
    message: 'Done! Reload your open Youtube tabs (or open a new one) to test the transparent player.'
  },
  cookies: { PREF: 'f6=400&gl=BR&hl=en', VISITOR_INFO1_LIVE: 'Q06SngRDTGA' }
}
3. PREF without hl=: { PREF: '&hl=en', VISITOR_INFO1_LIVE: 'Q06SngRDTGA' }
Enter fullscreen mode Exit fullscreen mode

Those three outputs confirm concrete runtime behavior from v0.4.0:

  1. On an empty cookie jar, chrome.runtime.onInstalled writes PREF=hl=en and VISITOR_INFO1_LIVE=Q06SngRDTGA.
  2. When options.js sends { type: "reinstall" }, onMessage returns true synchronously to keep the message port open across nested cookie callbacks, updates hl=pt to hl=en while keeping f6=400&gl=BR, and resolves a structured { success, message } payload.
  3. When PREF exists without an hl= parameter (f6=40000080), the legacy substring logic drops the existing key and leaves &hl=en, catching a subtle edge case before Chrome ever loads the extension.

Why It Works

Comparing the MV2 v0.3 commit (c84ba29) against the MV3 v0.4.0 commit (1865c5e) shows four core adaptations:

1. Splitting API permissions from host permissions

In Manifest V2, "cookies", "background", and "*://*.youtube.com/*" all lived inside permissions. Manifest V3 moves URL match patterns to host_permissions and replaces background.scripts with background.service_worker:

{
  "version": "0.4.0",
  "permissions": ["cookies"],
  "host_permissions": ["*://*.youtube.com/*"],
  "background": {
    "service_worker": "js/background.js"
  },
  "manifest_version": 3
}
Enter fullscreen mode Exit fullscreen mode

Without "*://*.youtube.com/*" in host_permissions, chrome.cookies calls cannot read or write .youtube.com cookies even when "cookies" is granted.

2. Moving alert() out of the service worker

In v0.3, createCookiePlayer() called alert(...) directly inside js/background.js. Because Manifest V3 service workers have no window or DOM globals, alert() throws a ReferenceError. In v0.4.0, createCookiePlayer(callback) invokes a completion callback, onMessage sends { success: true, message } through sendResponse, and js/options.js calls alert(message) inside options.html, where DOM APIs remain valid.

3. Replacing top-level startup execution with lifecycle listeners

MV2 executed getCookies(...) unconditionally when the script loaded and targeted http://youtube.com. v0.4.0 moves initialization into ensureYoutubeCookies() bound to chrome.runtime.onInstalled and chrome.runtime.onStartup, removes legacy Chrome 12-25 chrome.extension shims, and upgrades cookie URLs to https://www.youtube.com.

4. Preserving asynchronous sendResponse lifetimes

Because chrome.cookies.get and chrome.cookies.set use nested callbacks here, returning true from chrome.runtime.onMessage instructs Chrome to keep the response channel open until onReinstalled invokes sendResponse.

Failure Modes, Limitations, and Security Boundaries

Auditing the source and test output highlights important boundaries to keep in mind:

  • Retired YouTube experiment flag: VISITOR_INFO1_LIVE=Q06SngRDTGA targeted a 2015 YouTube player experiment that modern YouTube ignores. Treat this repository as an MV3 migration case study, not a working YouTube UI tweak.
  • PREF string slicing overwrites language and can drop parameters: changePreferences() forces hl=en (changing YouTube's UI language) and slices cookie.value with indexOf("hl=") and substr(...). When PREF lacks hl=, indexOf("hl=") returns -1 and substr(0, -1) returns "", wiping existing PREF flags. Production extensions should parse query-formatted cookie values with URLSearchParams.
  • Ephemeral worker memory and unconditional return true: cookieCache, cookieConfig, and cookiesLoaded reset whenever Chrome suspends the idle service worker, yet stay cached while the worker remains awake. Also, onMessage executes return true; outside if (request.type == "reinstall"); returning true only inside the handled branch prevents hanging unrecognized messages.
  • Residual MV2 artifacts: manifest.json retains "chrome_style": true inside options_ui (which logs an unrecognized-property warning in Chrome MV3), and YoutubeTransparentPlayer-mv3.zip still includes a legacy YoutubeTransparentPlayerProduction.zip file.
  • Cookie security boundary: Granting "cookies" plus "*://*.youtube.com/*" exposes cookies on .youtube.com to the extension. Audit cookie extensions in a node:vm harness or a throwaway --user-data-dir browser profile rather than a primary signed-in profile.

FAQ

Does v0.4.0 change the modern YouTube player UI?

No. It writes the VISITOR_INFO1_LIVE and PREF cookies as coded, but YouTube's frontend retired that 2015 player experiment.

Should I inspect v0.4.0 or master?

Pin the v0.4.0 tag (1865c5e) and its YoutubeTransparentPlayer-mv3.zip release asset for reproducible checks; master (557d42f) currently adds only a README.md update.

Why run background.js in Node.js before Chrome?

A compact node:vm harness tests onInstalled and onMessage deterministically in milliseconds, catches accidental window calls like alert(), and exposes string-parsing bugs without touching real browser cookies.

How do I silence Chrome's chrome_style manifest warning?

Remove "chrome_style": true from options_ui in manifest.json; Manifest V3 deprecated that Manifest V2 key.

Takeaway

Migrating a small cookie extension to Manifest V3 comes down to clean runtime boundaries: move URL patterns into host_permissions, keep UI calls like alert() out of the service worker, and return true only for asynchronous onMessage handlers that will call sendResponse. Pairing paladini/Youtube-Transparent-Player v0.4.0 with a short node:vm test script lets you verify both the MV3 migration and legacy cookie-parsing edge cases locally in seconds.

Disclosure: This tutorial was researched, drafted, and validated with AI assistance against the public paladini/Youtube-Transparent-Player repository, its v0.4.0 release artifact, commit diffs, and local Node.js execution.

When you migrate or review a browser extension for Manifest V3, do you validate service-worker messaging in a local Node harness first, or test directly in a disposable Chromium profile?

Top comments (0)