最近在使用 wxt 框架开发浏览器扩展,记录一些问题。

https://wxt.dev/

1. 隔离脚本与网站本身的样式

使用 Shadow Root,可以不让 content-scripts 侵入式影响网站本身,然后引入并渲染 App.vue 组件。

import './style.css';
import { createApp } from 'vue';
import App from './App.vue';

export default defineContentScript({
  matches: ['https://google.com/*'],
  cssInjectionMode: 'ui',

  async main(ctx) {
    const ui = await createShadowRootUi(ctx, {
      name: 'example-ui',
      position: 'inline',
      anchor: 'body',
      onMount: (container) => {
        const app = createApp(App);
        app.mount(container);
        return app;
      },
      onRemove: (app) => {
        app?.unmount();
      },
    });

    ui.mount();
  },
});

2. 在 config.js 中配置

import { defineConfig } from 'wxt';
import pkg from './package.json';

// See https://wxt.dev/api/config.html
export default defineConfig({
  extensionApi: 'chrome',
  modules: ['@wxt-dev/module-vue'],
  manifest: {
    name: 'xxx',
    version: pkg.version,
    description: ...,
    permissions: ['storage', 'scripting'] // 存储、插入脚本
  },
  hooks: {
    'build:manifestGenerated': (wxt, manifest) => {
      if (wxt.config.command === 'serve') {
        manifest.content_scripts ??= [];
        manifest.content_scripts.push({
          matches: ['https://google.com/*'],
          js: ['content-scripts/content.js'],
          css: ['content-scripts/content.css']
        });
      }
    }
  }
});