wxt-dev / wxt

⚡ Next-gen Web Extension Framework
https://wxt.dev
MIT License
4.35k stars 184 forks source link

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

Open aklinker1 opened 2 weeks ago

aklinker1 commented 2 weeks ago

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

aklinker1 commented 2 weeks ago

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