### Install and Run Vite Vue 3 Browser Extension Template Source: https://github.com/mubaidr/vite-vue3-browser-extension-v3/blob/master/README.md This snippet demonstrates the commands to quickly set up and run the Vite Vue 3 browser extension template. It involves cloning the template, installing dependencies, and starting the development server for Chrome or Firefox. ```bash npx degit mubaidr/vite-vue3-browser-extension-v3 my-webext cd my-webext npm install npm run dev ``` -------------------------------- ### Background Service Worker for Extension Lifecycle Source: https://context7.com/mubaidr/vite-vue3-browser-extension-v3/llms.txt Handles the installation and update events for the browser extension. It opens new tabs for setup or update pages based on the installation reason, and includes basic error handling for the service worker. ```typescript chrome.runtime.onInstalled.addListener(async (opt) => { if (opt.reason === "install") { chrome.tabs.create({ active: true, url: chrome.runtime.getURL("src/ui/setup/index.html") }) return } if (opt.reason === "update") { chrome.tabs.create({ active: true, url: chrome.runtime.getURL("src/ui/setup/index.html?type=update") }) return } }) self.onerror = function (message, source, lineno, colno, error) { console.info("Error: " + message) console.info("Source: " + source) console.info("Line: " + lineno) console.info("Column: " + colno) console.info("Error object: " + error) } console.info("Background service worker running") export {} ``` -------------------------------- ### Develop Vite Vue 3 Browser Extension for Chrome/Firefox Source: https://github.com/mubaidr/vite-vue3-browser-extension-v3/blob/master/README.md This snippet shows how to start the development server specifically for Chrome or Firefox browsers. This allows for rapid development and testing of the browser extension within the target browser environment. ```bash # Start development server for Chrome npm run dev:chrome # Start development server for Firefox npm run dev:firefox ``` -------------------------------- ### Vue Action Popup Component Example Source: https://context7.com/mubaidr/vite-vue3-browser-extension-v3/llms.txt An example Vue component for the browser extension's action popup. It utilizes Nuxt UI components and Vue Router for navigation to different sections like features, pricing, and login. It also includes links to external documentation and support. ```vue ``` -------------------------------- ### Launch Browsers with Vite Dev Servers Source: https://context7.com/mubaidr/vite-vue3-browser-extension-v3/llms.txt A Node.js script using commander for command-line argument parsing and concurrently for running multiple processes. It launches Vite development servers for different browser configurations and then starts the browsers using their respective commands. It supports launching Chrome, Firefox, and Edge. ```typescript // scripts/launch.ts import { exec } from "node:child_process" import { GetInstalledBrowsers } from "./getInstalledBrowsers" import concurrently from "concurrently" import { program } from "commander" program .option("-a, --all", "Launch All Supported Browsers", false) .option("-c, --chrome", "Launch Chrome only", true) .option("-f, --firefox", "Launch Firefox only", false) .option("-e, --edge", "Launch Edge only", false) .parse(process.argv) async function runViteDev() { console.info("Starting Vite dev servers...") const viteChrome = exec("vite dev --config vite.chrome.config.ts") const viteFirefox = exec("vite dev --config vite.firefox.config.ts") // Pipe output and handle exits } async function launchBrowsers() { const installedBrowsers = GetInstalledBrowsers() const commands = [] if (options.chrome && installedBrowsers.Chrome) { commands.push({ command: installedBrowsers.Chrome.command, name: installedBrowsers.Chrome.name }) } concurrently(commands, { killOthers: ["failure", "success"], restartTries: 1 }) } runViteDev().then(launchBrowsers) // Usage: npm run launch // Usage: npm run launch:all // Usage: tsx scripts/launch.ts --firefox --edge ``` -------------------------------- ### File-Based Router Configuration (TypeScript) Source: https://context7.com/mubaidr/vite-vue3-browser-extension-v3/llms.txt Configures the Vue Router using file-based routing. It imports auto-generated routes from the `vue-router/auto-routes` module and adds a catch-all route for redirection. This setup simplifies route management by automatically registering routes based on the file structure within specified directories. ```typescript // src/utils/router/index.ts import { createRouter, createWebHistory } from "vue-router" import { handleHotUpdate, routes } from "vue-router/auto-routes" // Add catch-all route routes.push({ path: "/:catchAll(.*)*", redirect: "/" }) export const appRouter = createRouter({ history: createWebHistory(import.meta.env.BASE_URL), routes }) // Hot module replacement support if (import.meta.hot) { handleHotUpdate(appRouter) } // Routes are auto-generated from: // src/ui/action-popup/pages/*.vue -> /action-popup/* // src/ui/options-page/pages/*.vue -> /options-page/* // src/ui/common/pages/*.vue -> /common/* ``` -------------------------------- ### Theme Switch Component (Vue) Source: https://context7.com/mubaidr/vite-vue3-browser-extension-v3/llms.txt A Vue component that provides a UI element for toggling between dark and light themes. It utilizes the `useTheme` composable to get the current theme state and the `toggleDark` function to switch themes. It dynamically sets the icon based on the current theme. ```vue ``` -------------------------------- ### Build and Lint Vite Vue 3 Browser Extension Project Source: https://github.com/mubaidr/vite-vue3-browser-extension-v3/blob/master/README.md These commands are used for building the browser extension for production and for running linting checks to maintain code quality. The build command prepares the extension files for deployment, while the lint command checks for code style and potential errors. ```bash # Build the extension for production npm run build # Lint the project code npm run lint ``` -------------------------------- ### Initialize Vue App with Router, i18n, and State Management Source: https://context7.com/mubaidr/vite-vue3-browser-extension-v3/llms.txt Sets up the main Vue application instance, integrating routing, internationalization, and Pinia state management. It also includes basic error handling for the browser environment. Dependencies include Vue core, router, i18n utilities, Pinia, and Nuxt UI. ```typescript import { i18n } from "src/utils/i18n" import { pinia } from "src/utils/pinia" import { appRouter } from "src/utils/router" import { createApp } from "vue" import App from "./app.vue" import ui from "@nuxt/ui/vue-plugin" import "./index.css" // Add context-specific redirect appRouter.addRoute({ path: "/", redirect: "/options-page" }) const app = createApp(App) .use(i18n) .use(ui) .use(pinia) .use(appRouter) app.mount("#app") self.onerror = function (message, source, lineno, colno, error) { console.info("Error: " + message) console.info("Source: " + source) console.info("Line: " + lineno) console.info("Column: " + colno) console.info("Error object: " + error) } export default app ``` -------------------------------- ### Pinia Store with Browser Storage Sync (TypeScript) Source: https://context7.com/mubaidr/vite-vue3-browser-extension-v3/llms.txt Defines a Pinia store that synchronizes its state with `chrome.storage.sync` and `chrome.storage.local` APIs. It uses custom composables `useBrowserSyncStorage` and `useBrowserLocalStorage` for seamless integration. State changes in the store are automatically persisted and available across different extension contexts. ```typescript // src/stores/options.store.ts export const useOptionsStore = defineStore("options", () => { const { isDark, toggleDark } = useTheme() const { data: profile } = useBrowserSyncStorage<{ name: string, age: number }>("profile", { name: "Mario", age: 24 }) const { data: others } = useBrowserLocalStorage<{ awesome: boolean, counter: number }>("options", { awesome: true, counter: 0 }) return { isDark, toggleDark, profile, others } }) // Usage in component: // const store = useOptionsStore() // store.profile.name = "Luigi" // Auto-syncs to chrome.storage.sync // store.others.counter++ // Auto-syncs to chrome.storage.local ``` -------------------------------- ### NPM Scripts for Vite Vue3 Browser Extension Development and Build Source: https://context7.com/mubaidr/vite-vue3-browser-extension-v3/llms.txt A collection of NPM scripts to manage the development, building, testing, and deployment of a Vite Vue3 browser extension. These scripts streamline workflows for multiple browsers (Chrome, Firefox) and include tasks for type checking, linting, formatting, and launching. ```bash # Development npm run dev # Start both Chrome and Firefox in development mode npm run dev:chrome # Start Chrome development server npm run dev:firefox # Start Firefox development server # Building npm run build # Build for both Chrome and Firefox (production) npm run build:chrome # Build for Chrome only npm run build:firefox # Build for Firefox only # Testing and Quality npm run typecheck # Run TypeScript type checking npm run lint # Run ESLint with auto-fix npm run lint:manifest # Validate manifest with web-ext npm run format # Format code with Prettier # Browser Launching npm run launch # Launch Chrome with extension loaded npm run launch:all # Launch all installed browsers # Output: # dist/chrome/ - Chrome extension files # dist/firefox/ - Firefox extension files # dist/chrome-1.0.0.zip - Chrome store upload package # dist/firefox-1.0.0.zip - Firefox store upload package ``` -------------------------------- ### Vite Build Configuration for Chrome Extension Source: https://context7.com/mubaidr/vite-vue3-browser-extension-v3/llms.txt Configures Vite for building a Chrome extension, including the CRX plugin for Manifest V3 compatibility and vite-plugin-zip-pack for creating distributable ZIP files. It merges base configurations and sets browser-specific output directories. ```typescript import { crx } from "@crxjs/vite-plugin" import { defineConfig, mergeConfig } from "vite" import zipPack from "vite-plugin-zip-pack" import manifest from "./manifest.chrome.config" import baseConfig from "./vite.config" const IS_DEV = process.env.NODE_ENV === "development" const browser = "chrome" const browserOutDir = `dist/${browser}` export default defineConfig(() => { const browserPlugins = [ crx({ manifest, browser, contentScripts: { injectCss: true } }) ] if (!IS_DEV) { browserPlugins.push( zipPack({ inDir: browserOutDir, outDir: "dist", outFileName: `${browser}-1.0.0.zip` }) ) } return mergeConfig(baseConfig, { build: { outDir: browserOutDir }, plugins: browserPlugins }) }) ``` -------------------------------- ### Theme Management Composable (TypeScript) Source: https://context7.com/mubaidr/vite-vue3-browser-extension-v3/llms.txt Manages dark/light theme state with persistence in `chrome.storage.local` and synchronization across contexts. It provides reactive properties like `mode` and `isDark`, and methods to `toggleDark` and `applyTheme`. The `applyTheme` function is useful for content scripts operating within a shadow DOM. ```typescript // Usage import { useTheme, applyTheme } from "@/composables/useTheme" const { mode, isDark, toggleDark, applyTheme } = useTheme() // Check current theme console.log(mode.value) // "dark" or "light" console.log(isDark.value) // true or false // Toggle theme toggleDark() // Set specific theme isDark.value = true // Switch to dark isDark.value = false // Switch to light // Manually apply theme (for content scripts with shadow DOM) applyTheme("dark") // Theme persists in chrome.storage.local and syncs across contexts // Automatically applies to document.documentElement or shadow root ``` -------------------------------- ### Reactive Chrome Storage Sync Composable (TypeScript) Source: https://context7.com/mubaidr/vite-vue3-browser-extension-v3/llms.txt A composable function to synchronize reactive data with `chrome.storage.sync`. It provides a reactive `data` object and a `promise` for initial load completion. Updates to the `data` object automatically sync across all extension contexts. It supports deep watching for changes. ```typescript // Usage import { useBrowserSyncStorage } from "@/composables/useBrowserStorage" const { data, promise } = useBrowserSyncStorage<{ username: string, preferences: { theme: string, language: string } }>("user-settings", { username: "guest", preferences: { theme: "dark", language: "en" } }) // Wait for initial load await promise // Read value console.log(data.value.username) // "guest" or stored value // Update value (automatically syncs across all extension contexts) data.value.username = "john_doe" data.value.preferences.theme = "light" // Listen for changes from other contexts watch(data, (newValue) => { console.log("Settings updated:", newValue) }, { deep: true }) ``` -------------------------------- ### Manifest Configuration for Browser Extensions Source: https://context7.com/mubaidr/vite-vue3-browser-extension-v3/llms.txt Defines the core configuration for a Manifest V3 browser extension, including name, version, background scripts, content scripts, and permissions. This central configuration can be extended for browser-specific overrides. ```typescript import type { ManifestV3Export } from "@crxjs/vite-plugin" export default { name: "My Extension", description: "Extension description", version: "1.0.0", manifest_version: 3, action: { default_popup: "src/ui/action-popup/index.html" }, background: { service_worker: "src/background/index.ts", type: "module" }, content_scripts: [ { all_frames: false, js: ["src/content-script/index.ts"], matches: ["*://*/*"], run_at: "document_end" } ], side_panel: { default_path: "src/ui/side-panel/index.html" }, devtools_page: "src/devtools/index.html", options_page: "src/ui/options-page/index.html", permissions: ["storage", "tabs", "background", "sidePanel"], host_permissions: [""] } as ManifestV3Export ``` -------------------------------- ### Reactive Chrome Storage Local Composable (TypeScript) Source: https://context7.com/mubaidr/vite-vue3-browser-extension-v3/llms.txt A composable function for syncing reactive data with `chrome.storage.local`. It returns a reactive `data` object and a `promise` for initial load. Changes to the `data` object are persisted locally. The composable ensures type safety and performs deep merging with default values, filling in missing fields or correcting types. ```typescript // Usage import { useBrowserLocalStorage } from "@/composables/useBrowserStorage" const { data, promise } = useBrowserLocalStorage<{ cacheData: string[], lastSync: number }>("app-cache", { cacheData: [], lastSync: Date.now() }) // Wait for initial load await promise // Update local storage data.value.cacheData.push("new-item") data.value.lastSync = Date.now() // Type safety and deep merge with defaults // If stored data has missing fields, they're filled with defaults // If stored data has wrong types, defaults are used ``` -------------------------------- ### Content Script for DOM Injection Source: https://context7.com/mubaidr/vite-vue3-browser-extension-v3/llms.txt Injects an iframe into the web page to render the extension's UI in an isolated context. It uses the DOMParser API and appends the iframe to the document body. Includes basic error handling for the content script. ```typescript import "./index.css" import { name } from "~/package.json" const src = chrome.runtime.getURL("src/ui/content-script-iframe/index.html") const iframe = new DOMParser().parseFromString( ``, "text/html" ).body.firstElementChild if (iframe) { document.body?.append(iframe) } self.onerror = function (message, source, lineno, colno, error) { console.info("Error: " + message) console.info("Source: " + source) console.info("Line: " + lineno) console.info("Column: " + colno) console.info("Error object: " + error) } console.info("Content script loaded") ``` -------------------------------- ### Configure Vue i18n for Multi-language Support Source: https://context7.com/mubaidr/vite-vue3-browser-extension-v3/llms.txt Configures the Vue I18n plugin for multi-language support, including messages from unplugin-vue-i18n. It persists the user's locale preference using browser local storage and watches for changes. Usage involves `useI18n` in components and message files in `src/locales`. ```typescript import messages from "@intlify/unplugin-vue-i18n/messages" import { createI18n } from "vue-i18n" export const i18n = createI18n({ globalInjection: true, legacy: false, locale: "en", fallbackLocale: "en", messages }) // Restore locale from local storage const { data } = useBrowserLocalStorage("user-locale", "en") i18n.global.locale.value = data.value // Watch for locale changes and persist watch(i18n.global.locale, (newLocale) => { data.value = newLocale }) // Usage in components: // const { t } = useI18n() //

{{ t('welcome.message') }}

// Message files: src/locales/en.json, src/locales/zh.json // { // "welcome": { // "message": "Welcome to the extension" // } // } ``` -------------------------------- ### Tailwind CSS Class Merging Utility (TypeScript) Source: https://context7.com/mubaidr/vite-vue3-browser-extension-v3/llms.txt A utility function `cn` for merging Tailwind CSS classes using `clsx` and `tailwind-merge`. It simplifies applying conditional and dynamic classes to elements, ensuring proper merging and deduplication of classes. Useful for component styling in Vue.js applications. ```typescript // src/lib/utils.ts import { type ClassValue, clsx } from 'clsx' import { twMerge } from 'tailwind-merge' export function cn(...inputs: ClassValue[]) { return twMerge(clsx(inputs)) } // Usage in components: // import { cn } from '@/lib/utils' // // const buttonClass = cn( // "px-4 py-2 rounded", // isDark && "bg-gray-800 text-white", // !isDark && "bg-white text-gray-800", // disabled && "opacity-50 cursor-not-allowed" // ) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.