Skip to content

Built-in support for Content Scripts running in SPAs #1029

Description

@aklinker1

Feature Request

Dealing with loading your content script correctly in SPAs is really annoying. WXT should be able to do it for you.

export default defineContentScript({
  matches: ['*://*.youtube.com/watch*'],
  spa: true,

  main(ctx) {
    console.log('YouTube content script loaded');
    mountUi(ctx);
  },
});

Is your feature request related to a bug?

N/A

What are the alternatives?

As the docs state, manually listening to URL changes works. But managing ctx correctly is annoying, and not shown in the docs. This would also create ctx for each URL path, so the script can shut down properly when the path changes.

Additional context

Screenshot 2024-10-03 at 1 01 49 PM

– https://discord.com/channels/1212416027611365476/1224500470278520904/1291359490121138207

Activity

  1. aklinker1 commented on Oct 3, 2024

    @aklinker1
    MemberAuthor

    This won't be an easy first-contribution, but it should be relatively easy to implement:

    1. Add new spa type for content script definition
    2. Implement a new "SPA handler" utility that manages context and the URL change listener.
    3. Add spa handler util to virtual entrypoints if spa: true
    4. Remove path from content script match patterns when spa: true, somehow passing the real match pattern into the util
  2. changed the title [-]Built-in support for Content Scripts running on SPAs[/-] [+]Built-in support for Content Scripts running in SPAs[/+] on Oct 3, 2024
  3. aklinker1 commented on May 26, 2026

    @aklinker1
    MemberAuthor

    I've implemented this in my own extension. There's a few TODOs, but it seems to be working well. It needs to be adapted into the form mentioned above, and we should mark it as experimental.

    https://github.com/anime-skip/player/blob/d62a241f92ee7c453d0d33e31939a5b741d0af5b/apps/extension/src/utils/define-spa-content-script.ts

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

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions