Published 2022-08-31

Chrome插件开发 - Custom options page

YyhZzD

向浏览器扩展添加可选项

打开manifest.json,添加 options 选项,注册选项页面。

{
  "options_ui": {
    "page": "options.html",
    "open_in_tab": false
  }
}

创建options.html

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>DDT Pop-up</title>
    <link rel="stylesheet" type="text/css" href="./css/style.css" />
  </head>
  <body>
    <div id="options"></div>
    <script type="module" src="src/options/index.jsx"></script>
  </body>
</html>

修改src/index.jsx

import ReactDOM from 'react-dom'
import {App} from './App'

const app = document.getElementById('options')
ReactDOM.render(<App />, app)

修改src/App.jsx

import {useState} from 'react'

export function App() {
  const [color, setColor] = useState('indigo')

  chrome.storage.sync.get('color', (storedColor) => {
    setColor(storedColor.color)
  })

  const pickColor = (pickedValue) => {
    setColor(pickedValue)
    chrome.storage.sync.set({color: pickedValue})
    window.close()
  }

  return (
    <div className="m-4">
      <select
        onChange={(event) => pickColor(event.target.value)}
        value={color}
        className="block w-full p-4 text-sm text-gray-900 border border-gray-300 rounded-lg bg-gray-50 focus:ring-indigo-500 focus:border-indigo-500 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-indigo-500 dark:focus:border-indigo-500"
      >
        <option>Pick a color</option>
        <option value="indigo">Indigo</option>
        <option value="pink">Pink</option>
        <option value="purple">Purple</option>
        <option value="red">Red</option>
      </select>
    </div>
  )
}

修改vite.config.js,多页面打包配置

import {defineConfig} from 'vite'
const {resolve} = require('path')
import react from '@vitejs/plugin-react'

export default defineConfig({
  plugins: [react()],
  build: {
    rollupOptions: {
      input: {
        main: resolve(__dirname, 'index.html'),
        options: resolve(__dirname, 'options.html')
      }
    }
  }
})

最终效果如下:

<video src="https://cdn.jsdelivr.net/gh/manonicu/pics@master/uPic/options_zuppir.webm" autoPlay

Source Code

【Source Code】