Skip to content

Register a defined Content Script at runtime #2040

Description

@mptr

Feature Request

I use defineContentScript() for some Logic behind Feature-Toggles. To dynamically inject them I have set registration: "runtime", as well.
When I now try to inject these at runtime using browser.scripting.registerContentScripts() I have to specify paths to css and js artifacts generated from my content script directory (e.g. bundled css files from scss code). This pretty much defeats the purpose of the easy to use wxt build system.

I would like to be able to reference my defined Content Script with variable/import References, for example like this:

// entrypoints/my.content/index.ts
export default defineContentScript({ registration: "runtime", ... })
// entrypoints/background.ts
import myContent from "./entrypoints/my.content";
export default defineBackground(() => {
	browser.scripting.registerContentScripts([myContent]); // <- not possible because types do not match
	// post-bundle information on the script (and its parts) is not exposed

	// ... some time later
	browser.scripting.unregisterContentScripts([myContent]);
});

Is your feature request related to a bug?

"N/A"

What are the alternatives?

Working around this by looking into the built artifacts and specifying every file for every content script manually.

Additional context

Activity

  1. added theissue type on Jan 15, 2026
  2. marcellino-ornelas commented on Apr 10, 2026

    @marcellino-ornelas
    Contributor

    Until something is changed here what you can do is use a wxt module to do this for you. We are currently doing this right now.

    Here some guides:

    import { optionalContentScripts } from '#optional-content-scripts';
    
    const ID_PREFIX = 'optional:';
    
    function getScriptId(js: string[]): string {
        return `${ID_PREFIX}${js[0]}`;
    }
    
    export async function registerOptionalContentScripts(): Promise<void> {
        const registered = await browser.scripting.getRegisteredContentScripts();
    
        // Unregister any stale optional scripts from previous versions
        const staleIds = registered
            .filter((s) => s.id.startsWith(ID_PREFIX))
            .map((s) => s.id);
    
        if (staleIds.length > 0) {
            await browser.scripting.unregisterContentScripts({ ids: staleIds });
        }
    
        if (optionalContentScripts.length === 0) return;
    
        // Register current optional content scripts
        await browser.scripting.registerContentScripts(
            optionalContentScripts.map((script) => ({
                ...script,
                id: getScriptId(script.js),
            })) as Browser.scripting.RegisteredContentScript[]
        );
    }
  3. marcellino-ornelas commented on Apr 10, 2026

    @marcellino-ornelas
    Contributor

    Still would like to see this as a first class wxt feature tho 🙌🏽

  4. aklinker1 commented on Apr 11, 2026

    @aklinker1
    Member

    I'd be down to create an official WXT module for this, similar to @wxt-dev/auto-icons. I don't think every WXT project needs this, so it shouldn't go in the core wxt package.

    Generating a module in the .wxt dir like @marcellino-ornelas mentioned is the "correct" way to do this today. This is what you should do anytime you need to create and reference generated variables.

  5. added
    good first issue
    on Apr 11, 2026
  6. andoan16 commented on Apr 13, 2026

    @andoan16

    Auto-closing: linked PR #2258 was closed (CI checks failed). Sorry for the inconvenience.

  7. silverfish2525 commented on Jun 25, 2026

    @silverfish2525
    Contributor

    @aklinker1 — I can take this on as a separate @wxt-dev/* module. Before I open a PR, can you sanity-check the shape?

    Read your comments across #2239 and #2288. As I understand it: the build-system side stays in core (PR #2288, with optionalMatches
    always going to optional_host_permissions per your May 12 call), and the runtime orchestration sits outside core. This module would be
    the runtime orchestration piece — purely surfacing the metadata WXT already has so the user can call
    browser.scripting.registerContentScripts() themselves. Dev reload already only updates existing user-registered scripts
    (reloadRuntimeContentScriptMv3 calls updateContentScripts, never registerContentScripts), so the module just emits a typed array
    the user passes to their own registration call.

    // wxt.config.ts
    export default defineConfig({
      modules: ['@wxt-dev/runtime-content-scripts'],
    });
    
    // entrypoints/background.ts
    import {
      runtimeContentScripts,
      registerRuntimeContentScripts,
    } from '#runtime-content-scripts';
    
    browser.runtime.onInstalled.addListener(async () => {
      await registerRuntimeContentScripts();
      // or directly: await browser.scripting.registerContentScripts(runtimeContentScripts);
    });

    Open questions:

    1. Name. @wxt-dev/runtime-content-scripts is most literal but overlaps the keyword; @wxt-dev/dynamic-content-scripts reads
      cleaner. Preference?

    2. Helper or just the array for v0? Helper would do unregister-stale + register with a prefixed ID scheme (default
      wxt-rcs:<name>), so calling it from onInstalled is idempotent. Otherwise just the array.

    3. optionalMatches (per your feat: add content script registration optional #2288 pivot). Once that lands, the module would surface those separately — e.g.
      runtimeContentScripts for required matches, plus optionalContentScripts (or a sibling field on the same descriptor) for
      optionalMatches so the user can register those after the permission grant. Sound right, or did you have a different shape in mind?

    4. getEntrypointBundlePath is internal. Happy to copy the small bit I need locally — only worth exposing from wxt/modules if
      you'd prefer to keep that logic in one place.

    5. Timing. Wait for feat: add content script registration optional #2288 to actually land before I open a PR, or fine to start scaffolding now against your stated direction?

    I'll hold off on the PR until you've weighed in.

  8. aklinker1 commented on Jun 28, 2026

    @aklinker1
    Member

    @silverfish2525 let's circle back to the original problem: The OP doesn't want to pass the bundled paths as a string literal since it may change over time as the file is moved/renamed. Registering content scripts is just one example of a place where this would be useful, but it would also be useful for any functions that require a file path, like browser.runtime.getURL.

    A simple solution to this would be to add a ref option (or something else) to entrypoints that you can set and doesn't change when the file is renamed:

    // content.ts
    export default defineContentScript({
      ref: "CUSTOM_NAME",
      ...
    })

    Then the module would generate a file like this:

    // .wxt/entrypoints.ts
    export const ENTRYPOINT_CUSTOM_NAME = "/content-scripts/content.js"

    Any you import it like import { ENTRYPOINT_CUSTOM_NAME } from '#entrypoints'

    I would probably name this something like @wxt-dev/entrypoint-refs.


    I'm not opposed to a module that does what you describe, but it seems quite niche - do all extensions that use dynamically registered content scripts need the behavior you described? Could you explain your use-case more so I have more context?

    It just seems like there was a logical jump here I'm missing.

  9. silverfish2525 commented on Jun 29, 2026

    @silverfish2525
    Contributor

    @aklinker1 Not all — only extensions using registration: 'runtime'.

    Before starting on packages/entrypoint-refs/:

    • CSS: content scripts need both paths — { js, css } object or plain string?
    • Opt-in or auto: explicit ref: 'NAME' only, or every entrypoint by default?
    • HTML entrypoints (ENTRYPOINT_POPUP = '/popup.html') in scope?
  10. aklinker1 commented on Jun 29, 2026

    @aklinker1
    Member
    1. CSS: content scripts need both paths — { js, css } object or plain string?

    You decide - whatever feels better once you have something up and running works for me.

    1. Opt-in or auto: explicit ref: 'NAME' only, or every entrypoint by default?

    If the separate module is installed and setup, I assume people want references for each entrypoint. So let's make it auto, using the entrypoint name by default, but respect custom refs.

    1. HTML entrypoints (ENTRYPOINT_POPUP = '/popup.html') in scope?

    Yes, I would say all entrypoints should be given a variable in the generated module.

  11. aklinker1 commented on Jun 29, 2026

    @aklinker1
    Member

    Also, to respond to some of your other question that's relevant:

    getEntrypointBundlePath is internal. Happy to copy the small bit I need locally — only worth exposing from wxt/modules if
    you'd prefer to keep that logic in one place.

    We can export it from wxt. That's be better than wxt/modules in this case, it can be used by other code, not just modules.

    Please do this in a separate PR.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    contribution welcomegood first issue

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions