Fix "Duplicate script ID" from chrome.scripting.registerContentScripts
6 min readModerok team
Why chrome.scripting.registerContentScripts rejects with "Duplicate script ID", the unregister-first fix, and what still breaks in Chrome and Firefox.
If your MV3 service worker rejects with Error: Duplicate script ID 'page-watcher', the id is already registered and Chrome will not take it twice. Clear your dynamic registrations before you add them, from one place, and catch the rejection:
const SCRIPTS = [
{ id: "page-watcher", matches: ["https://example.com/*"], js: ["content.js"] },
];
async function register() {
await chrome.scripting.unregisterContentScripts();
await chrome.scripting.registerContentScripts(SCRIPTS);
}
chrome.runtime.onInstalled.addListener(() => {
register().catch((error) => console.error("[register]", error));
});
Chrome's scripting reference states the failure condition directly: "If there are errors during script parsing/file validation, or if the IDs specified already exist, then no scripts are registered." Not "the duplicate is skipped": the whole call fails and nothing lands. Everything below is why the id was already there, and what still bites after the fix.
Why the id is already registered
This surprises people because a dynamic registration is not service-worker state. It outlives the worker, and it outlives the browser.
That is the documented default. Chrome says of persistAcrossSessions on RegisteredContentScript: "Specifies if this content script will persist into future sessions. The default is true." MDN spells the same default out in more detail: "Specifies if this content script persists across browser restarts and updates and extension restarts. Defaults to true." MDN then qualifies that for updates, which is covered below.
So the usual sequence is: your worker registers page-watcher, goes idle, and Chrome tears it down, which is normal rather than a bug. Something later wakes the worker, top-level code runs again, the registration call runs again, and the first registration is still there, so this one rejects.
Registering at the top level of background.js, registering in both onInstalled and onStartup, or re-registering after a browser restart will each do it.
Register in one place, and make it idempotent
chrome.scripting.unregisterContentScripts() with no filter is the blunt instrument that makes the whole thing idempotent. The reference says: "If specified, only unregisters dynamic content scripts which match the filter. Otherwise, all of the extension's dynamic content scripts are unregistered." No filter means a clean slate, so the register call that follows cannot collide.
A manifest for the snippet above, with the keys Chrome lists as required by the Extensions platform (manifest_version, name, version) plus what this needs (Chrome lists description and icons separately, as required by the Web Store):
{
"manifest_version": 3,
"name": "Page watcher",
"version": "1.0.0",
"background": { "service_worker": "background.js" },
"permissions": ["scripting"],
"host_permissions": ["https://example.com/*"]
}
scripting is the API permission, and you need host access for the pages you inject into. The scripting reference gives the two ways to get it: "Use the "host_permissions" key or the "activeTab" permission, which grants temporary host permissions."
Wiping everything has one cost: it also drops registrations you wanted to keep, which matters if your extension registers scripts per site as users opt in. In that case reconcile only the ids you own, and serialize the work:
const IDS = SCRIPTS.map((script) => script.id);
let queue = Promise.resolve();
function ensureRegistered() {
queue = queue
.then(async () => {
const existing = await chrome.scripting.getRegisteredContentScripts({ ids: IDS });
const have = new Set(existing.map((script) => script.id));
const toUpdate = SCRIPTS.filter((script) => have.has(script.id));
const toAdd = SCRIPTS.filter((script) => !have.has(script.id));
if (toUpdate.length) await chrome.scripting.updateContentScripts(toUpdate);
if (toAdd.length) await chrome.scripting.registerContentScripts(toAdd);
})
.catch((error) => console.error("[ensure]", error));
return queue;
}
chrome.runtime.onInstalled.addListener(() => ensureRegistered());
getRegisteredContentScripts() "returns all dynamically registered content scripts for this extension that match the given filter". This version only adds and updates: it never unregisters an id you have since dropped from SCRIPTS, so remove those explicitly.
Two traps in the obvious version
The shorter version most people write first branches on whether anything came back:
const existing = await chrome.scripting.getRegisteredContentScripts({ ids: IDS });
if (existing.length) await chrome.scripting.updateContentScripts(SCRIPTS);
else await chrome.scripting.registerContentScripts(SCRIPTS);
It has two defects, which is why the version above splits the list and runs it through a queue.
The filter returns a subset. If one of three ids is registered and the other two are not, existing.length is truthy, so every id goes to updateContentScripts, and that call fails wholesale: the reference says it does nothing if "the IDs specified do not correspond to a fully registered script". The partial case is exactly the per-site case.
The check and the write are two awaits. If two things call it within a few milliseconds, both can see nothing registered and both call registerContentScripts. The second loses. The WXT framework hit this shape in its dev-mode reload path, logging Duplicate script ID 'wxt:content-scripts/ttd.js' twice three milliseconds apart, because one file save emitted several reload events and each read the registration list before the other's write completed. Chaining onto a single module-level promise closes that window; falling back to updateContentScripts on the duplicate error does not, because the winning registration may not be fully registered yet.
What still breaks after the fix
Already-open tabs get nothing. Registration is a standing instruction for future page loads: MDN describes scripting.registerContentScripts() as the way to "ask the browser to load a content script whenever the browser loads a page whose URL matches a given pattern". A W3C WebExtensions issue proposing a deny-list API lists the consequence among its problems: "scripting.registerContentScripts() does not inject the script into already existing tabs." If the script needs to run in tabs the user already has open, follow the registration with chrome.scripting.executeScript against those tabs. That path needs host permissions or activeTab for those tabs, per the same permissions note above.
Unregistering does not undo injection. A key point beside the reference's unregister example: "Unregistering content scripts will not remove scripts or styles that have already been injected." The listeners and DOM changes your script already made stay live in those documents until they reload.
Do not assume registrations survive an extension update. MDN's RegisteredContentScript page contradicts itself. The persistAcrossSessions sentence quoted earlier, on that page, says registrations persist across updates. The note printed directly beneath it, on the same page, says the opposite: "When an extension updates, content scripts are cleared. To restore scripts, add code to the extension's runtime.onInstalled event handler that responds to the "update" reason." Chrome's reference says nothing either way. Registering in onInstalled without filtering on details.reason costs nothing and is correct under both readings, which is why the first snippet does not filter.
Ids starting with an underscore are rejected. The reference says of the id property: "Must not start with a '_' as it's reserved as a prefix for generated script IDs." If you derive ids from file paths, strip leading underscores.
A missing file fails the whole call too. The sentence that covers duplicate ids also covers "errors during script parsing/file validation". A typo in a js path produces a rejection, not a silent skip, and still registers nothing from that batch.
Firefox differences
Firefox documents the same error condition, worded differently: "Errors can occur during script parsing and file validation or if the IDs specified exist. When an error occurs, no scripts are registered."
Availability differs by manifest version. MDN: "This method is available in Manifest V3 or higher in Chrome and Firefox 101. In Firefox 102+, this method is also available in Manifest V2." Firefox also still carries the older contentScripts API, which MDN marks as "only in Manifest V2 in Firefox". New code should use scripting instead.
One CSS detail is easy to miss when porting. MDN notes of runAt: "In Firefox, runAt also affects the point where the CSS is inserted. In Chrome, runAt does not affect the CSS insertion point." If a registered script ships css as well as js, the stylesheet can land at a different moment in the two browsers.
Seeing this in production
A rejected registerContentScripts call with nothing catching it becomes an unhandled promise rejection in a context nobody has DevTools attached to. The extension looks installed, the manifest is fine, and the script simply never runs for some users.
That is the class of failure the Moderok SDK records for you: with error tracking on by default, uncaught exceptions and unhandled promise rejections in any context where you call Moderok.init() are sent as __error events. One catch, literally: the .catch() in the snippets above makes the rejection handled, so it no longer arrives on its own. Report it from inside that handler with Moderok.captureError(error, { step: "registerContentScripts" }). The error tracking guide covers both paths.