内容脚本(Content Scripts)

CRXJS为内容脚本提供Vite HMR。

静态资源

可以随意导入静态资源!CRXJS会自动将导入的内容脚本依赖项声明为清单中的web_accessible_resources

使用扩展URL

内容脚本共享宿主页面的来源,因此使用Chrome API将导入的静态资源转换为扩展来源。

import logo from './logo.png'
const url = chrome.runtime.getURL(logo)

内容脚本中的HTML

可以使用iframe将扩展页面注入到宿主页面中。即使宿主页面指定了frame-src策略,宿主页面的CSP也不会影响注入的iframe。

注入的扩展页面加载在跨域iframe中,因此它不像内容脚本那样可以访问宿主页面的DOM。

content-script.js
const src = chrome.runtime.getURL('pages/iframe.html')

const iframe = new DOMParser().parseFromString(
  `<iframe class="crx" src="${src}"></iframe>`,
).body.firstElementChild

document.body.append(iframe)

然而,注入的扩展页面确实可以访问完整的Chrome API。

如果从内容脚本加载HTML文件,您需要将该文件声明为web可访问资源。

manifest.config.ts
import { defineManifest } from '@crxjs/vite-plugin'
import pkg from './package.json'

export default defineManifest({
  manifest_version: 3,
  name: pkg.name,
  version: pkg.version,
  action: {
    default_popup: 'src/popup/index.html',
  },
  content_scripts: [{
    js: ['src/content/main.ts'],
    matches: ['https://*/*'],
  }],
  web_accessible_resources: [{
      resources: ["pages/iframe.html"],
      matches: ["https://*.google.com/*"]
  }]
})

您还需要将HTML文件添加到Vite配置的build.rollupOptions.input下。

vite.config.ts
export default defineConfig({
  build: {
    rollupOptions: {
      input: {
        welcome: 'pages/iframe.html',
      },
    },
  },
})

导入的HTML

如果需要在没有框架的情况下在内容脚本中渲染复杂的HTML,可以通过使用?raw查询将其作为文本导入,HTML文件可以作为静态片段。此技术不需要文件是web可访问的,也不需要您在Vite配置中声明它。

import html from './root.html?raw'

const iframe = new DOMParser().parseFromString(html).body.firstElementChild
iframe.src = chrome.runtime.getURL('pages/iframe.html')

document.body.append(iframe)

将HTML文件作为文本导入可以让您利用IDE的语言服务功能来处理HTML文件。根据您的HTML内容,这种技术可能比使用document.createElement()更简洁。