From f6232676e0e44d005f1793a0ada0b1aa02af0f8a Mon Sep 17 00:00:00 2001 From: Adriaan van Rossum <1079135+adriaanvanrossum@users.noreply.github.com> Date: Tue, 21 Apr 2026 16:20:34 +0200 Subject: [PATCH] Fix Chrome detection breaking onBeforeRequest listener Recent Chrome MV3 versions expose a `browser` global alias, which caused `IS_FIREFOX` to incorrectly evaluate to `true` in Chrome. The extension then tried to register a blocking `chrome.webRequest.onBeforeRequest` listener that doesn't exist in the Chrome MV3 manifest, throwing "Cannot read properties of undefined (reading 'onBeforeRequest')". Switch to feature-detecting `declarativeNetRequest` vs. blocking `webRequest` so Chrome uses dynamic rules and Firefox keeps using webRequest. Also guard `updateListeners` against a missing `chrome.webRequest.onBeforeRequest` as a defensive fallback. --- background.js | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/background.js b/background.js index c330202..669a395 100644 --- a/background.js +++ b/background.js @@ -4,9 +4,14 @@ let blocklist = []; let tabs = {}; -// Detect if the extension is running in Firefox +// Detect if the extension is running in Firefox. +// Chrome (MV3) exposes `chrome.declarativeNetRequest` but no blocking +// `chrome.webRequest`. Recent Chrome versions also expose a `browser` global, +// so we can't rely on that. Feature-detect the APIs we actually need instead. const IS_FIREFOX = - typeof browser !== "undefined" && typeof browser.runtime !== "undefined"; + typeof chrome.declarativeNetRequest === "undefined" && + typeof chrome.webRequest !== "undefined" && + typeof chrome.webRequest.onBeforeRequest !== "undefined"; const DEBUG = false; const debug = (...messages) => { @@ -214,6 +219,13 @@ function updateListeners(blocklistLocal) { if (IS_FIREFOX) { // Firefox: Use webRequest API + if (!chrome.webRequest || !chrome.webRequest.onBeforeRequest) { + console.warn( + "chrome.webRequest.onBeforeRequest is not available; skipping listener update." + ); + return; + } + const urls = blocklist.reduce((list, { enabled, scripts = [] }) => { if (!enabled) return list; const add = scripts