vite-vue3-browser-extension-v3

repository·master·Indexed 21 days ago

https://github.com/mubaidr/vite-vue3-browser-extension-v3

A modern starter template for building Manifest V3 browser extensions using Vite and Vue 3. It features a multi-context architecture supporting background scripts, content scripts, popups, side panels, and devtools. The project includes file-based routing for UI pages, Pinia for state management, and compatibility layers via webext-bridge and webextension-polyfill for cross-browser support (Chrome and Firefox).

Tokens
10.2K
Snippets
31
Records
45
Agent score
73%

What's inside vite-vue3-browser-extension-v3

  1. Understand the Project Architecture

    master

    The project is built as a multi-context extension supporting various browser environments including background scripts, popups, options pages, content scripts, devtools, side panels, and offscreen pages.

    Key architectural features include:

    • File-Based Routing: UI routes are automatically registered based on the directory structure in src/ui/*/pages.
    • Modular UI Stack: Uses Nuxt/UI v3 and shadcn-vue for components, styled with Tailwind CSS 4.
    • State & Logic: Leverages Vue 3 Composition API, Pinia for state management, and custom composables for i18n, theme, and storage.
    • Compatibility: Uses webext-bridge and webextension-polyfill to ensure WebExtension API compatibility across different browsers.
  2. Navigate the Folder Structure

    master

    The project follows a strict directory structure to separate different extension contexts and shared logic:

    • src/assets/: Global assets like CSS and images.
    • src/background/: Background scripts handling lifecycle and install/update logic.
    • src/components/: Shared Vue components.
    • src/composables/: Vue composables (hooks).
    • src/content-script/: Content scripts for DOM injection and page interaction.
    • src/devtools/, src/offscreen/, src/side-panel/: Specialized extension contexts.
    • src/stores/: Pinia stores for state management.
    • src/types/: TypeScript definitions.
    • src/ui/: UI entrypoints (e.g., popup, options, setup).
    • src/utils/: Shared utilities (router, i18n, pinia, etc.).
    • src/modules/: (Implied by architecture) Modular logic components.
  3. Understand the Project Structure

    master

    The project follows a specific directory layout to manage different extension contexts and shared logic:

    • src/background/: Background service worker logic.
    • src/components/: Shared Vue components.
    • src/composables/: Vue composables (hooks).
    • src/content-script/: Content scripts that run in the context of web pages.
    • src/devtools/: DevTools panel implementation.
    • src/offscreen/: Offscreen documents.
    • src/stores/: Pinia state management stores.
    • src/ui/: UI entrypoints (e.g., popup, options).
      • src/ui/*/pages/: Uses file-based routing for UI pages.
    • src/types/: TypeScript definitions.
    • src/utils/: Shared utility functions.
  4. Follow Coding Conventions and Best Practices

    master

    When developing with this project, adhere to the following standards:

    Development Standards:

    • Use TypeScript and the Vue 3 Composition API (<script setup>).
    • Use Pinia for state management and Vue Router for navigation.
    • Utilize Auto-Imports for functions, stores, and components.
    • Use shadcn-vue for accessible and customizable UI components.

    Logic & Error Handling:

    • Use composables for cross-cutting concerns like theme, i18n, and storage.
    • Handle errors gracefully. When working in background or content scripts, use console.info for logging.
  5. Quick Start with Vite Vue 3 Browser Extension

    master

    To create a new project using this template, use degit to scaffold the repository, install dependencies, and start the development server.

    Note: The npm run dev command starts development environments for both Chrome and Firefox simultaneously.

    npx degit mubaidr/vite-vue3-browser-extension-v3 my-webext
    cd my-webext
    npm install
    npm run dev
  6. Handle initial storage loading with the promise return

    master

    Both useBrowserSyncStorage and useBrowserLocalStorage return a promise. Because reading from chrome.storage is asynchronous, you should await this promise before relying on the data value to ensure that the initial state reflects what is actually stored in the browser, rather than just the defaultValue provided.

    const { data, promise } = useBrowserSyncStorage('my_key', 'default')
    
    // Do this to ensure 'data' is populated from storage before use
    await promise
    console.log(data.value) // This will be the actual stored value
  7. Understand the file-based typed routing system

    master

    This project uses a file-based routing system powered by vue-router and sfc-typed-router. The routing configuration is automatically generated into src/types/typed-router.d.ts.

    Key aspects of this system:

    1. Automatic Type Generation: The RouteNamedMap interface provides a type-safe map of all available routes in the application. This allows for type-safe navigation and route parameter handling.
    2. Volar Integration: The generated types are designed to be used by the sfc-typed-router Volar plugin. This enables automatic typing for useRoute() within your Single File Components (SFCs).
    3. Route Structure: Routes are mapped from their file paths. For example, a file at src/ui/options-page/pages/index.vue corresponds to the route '/options-page/'.

    Note: This file is automatically generated. DO NOT MODIFY THIS FILE MANUALLY. To update the routes, modify your file structure in the src/ui/.../pages/ directories and allow the generator to run.

  8. How the content script injects the UI iframe

    master

    The content script functions by injecting an <iframe> directly into the document.body of the host web page. This iframe loads a specific HTML entrypoint (src/ui/content-script-iframe/index.html) using the extension's internal URL via chrome.runtime.getURL.

    Key characteristics of the injected iframe:

    • CSS Class: It is assigned the class crx-iframe and a class name derived from the project's package.json name.
    • Styling: It relies on ./index.css (imported within the content script) for its initial styling.
    • Accessibility: It includes a title attribute matching the extension name.
    // The content script logic effectively performs this operation:
    const src = chrome.runtime.getURL("src/ui/content-script-iframe/index.html");
    const iframe = new DOMParser().parseFromString(
      `<iframe class="crx-iframe ${name}" src="${src}" title="${name}"></iframe>`,
      "text/html"
    ).body.firstElementChild;
    
    if (iframe) {
      document.body?.append(iframe);
    }
  9. Data integrity and type safety in browser storage

    master

    The storage composables enforce type consistency to prevent corrupting stored data.

    • Type Matching: When updating data, the new value must match the type of the defaultValue. If a type mismatch occurs (e.g., trying to save a string where a boolean was expected), the update will be rejected and an error will be logged.
    • Deep Merging: If the defaultValue is an object, the composable performs a deep merge when loading data from storage. This allows you to add new properties to your default configuration object without losing existing user settings for older properties.
    • Supported Types: The system validates types for strings, booleans, nulls, and arrays.