### Initialize Plasmo Extension with Example Template Source: https://github.com/plasmohq/docs/blob/main/src/pages/framework/workflows/new.mdx Command to generate a Plasmo extension project based on a pre-defined example template. The `--with-env` flag is used here to specify the 'with-env' example from the Plasmo examples repository. Note the `--` separator required for npm. ```sh pnpm create plasmo --with-env # OR npm create plasmo -- --with-env ``` -------------------------------- ### Initialize Plasmo Extension Project with Name Source: https://github.com/plasmohq/docs/blob/main/src/pages/framework/workflows/new.mdx Command to initialize a Plasmo extension project and skip the naming prompt by providing the extension name as an argument. Useful for automation or quick setup. ```sh pnpm create plasmo "My Awesome Extension" # OR yarn create plasmo "My Awesome Extension" # OR npm create plasmo "My Awesome Extension" ``` -------------------------------- ### Install Puro for React Context Source: https://github.com/plasmohq/docs/blob/main/src/pages/quickstarts/with-stripe.mdx Adds `puro`, Plasmo's context utility library, as a dependency to the project's `package.json`. This library simplifies the creation of React contexts. ```json { ... "dependencies": { ... "puro": "0.3.4" } } ``` -------------------------------- ### Create Plasmo Project with TailwindCSS (Bash) Source: https://github.com/plasmohq/docs/blob/main/src/pages/quickstarts/with-tailwindcss.mdx Command to quickly scaffold a new Plasmo project pre-configured with Tailwind CSS. This is the simplest way to start a project with Tailwind integration. ```bash pnpm create plasmo --with-tailwindcss ``` -------------------------------- ### Initialize Plasmo Project with Supabase Source: https://github.com/plasmohq/docs/blob/main/src/pages/quickstarts/with-supabase.mdx This command initializes a new Plasmo project and configures it to use Supabase. ```bash pnpm create plasmo --with-supabase ``` -------------------------------- ### Initialize Plasmo Extension with Specific Entry Files Source: https://github.com/plasmohq/docs/blob/main/src/pages/framework/workflows/new.mdx Command to create a Plasmo extension project with custom entry files. The `--entry` flag accepts a comma-separated list of entry file names (without extensions). Note the `--` separator required for npm. ```sh pnpm create plasmo --entry=options,newtab,contents/inline # OR npm create plasmo -- --entry=options,newtab,contents/inline ``` -------------------------------- ### Install Firebase Auth Dependencies (npm, yarn, pnpm) Source: https://github.com/plasmohq/docs/blob/main/src/pages/quickstarts/with-firebase-authentication.mdx Installs the necessary packages for Firebase authentication, Plasmo messaging, and Plasmo storage. These commands are compatible with npm, yarn, and pnpm package managers. ```shell npm install firebase @plasmohq/messaging @plasmohq/storage ``` ```shell yarn add firebase @plasmohq/messaging @plasmohq/storage ``` ```shell pnpm install firebase @plasmohq/messaging @plasmohq/storage ``` -------------------------------- ### Install TailwindCSS Dependencies (Bash) Source: https://github.com/plasmohq/docs/blob/main/src/pages/quickstarts/with-tailwindcss.mdx Command to add Tailwind CSS, PostCSS, and Autoprefixer as development dependencies to an existing Plasmo project. These packages are essential for Tailwind CSS to function. ```bash pnpm i -D tailwindcss@3 postcss autoprefixer ``` -------------------------------- ### Create Plasmo Project with `src` Directory (Bash) Source: https://github.com/plasmohq/docs/blob/main/src/pages/framework/customization/src.mdx Use this command to create a new Plasmo project with the source code files organized within an `src` directory from the start. This leverages Plasmo's example template feature. ```bash pnpm create plasmo --with-src ``` -------------------------------- ### Storage API: Installation and Usage Source: https://context7.com/plasmohq/docs/llms.txt This section details the installation and basic usage of the Plasmo Storage API, which provides synchronized, persistent storage across all extension contexts. It covers setting and getting data, including complex objects, and watching for changes. The API falls back to `localStorage` when extension storage is unavailable. ```bash pnpm install @plasmohq/storage ``` ```typescript // background.ts or any extension context import { Storage } from "@plasmohq/storage" const storage = new Storage({ area: "local" // or "sync", "managed", "session" }) // Store complex objects without JSON.stringify await storage.set("user", { id: 123, name: "John Doe", preferences: { theme: "dark" } }) const user = await storage.get("user") console.log(user.name) // "John Doe" // Watch for changes across contexts storage.watch({ "user": (change) => { console.log("User updated:", change.newValue) console.log("Previous value:", change.oldValue) } }) // Update from another context (popup, content script, etc) await storage.set("user", { ...user, name: "Jane Smith" }) // Watch callback fires automatically ``` -------------------------------- ### Messaging API: Type-Safe Communication (Install and Background) Source: https://context7.com/plasmohq/docs/llms.txt This section covers the installation and setup of the Plasmo Messaging API for type-safe communication between extension components. It shows the installation command and the structure for defining message handlers in the background script. ```bash pnpm install @plasmohq/messaging ``` ```typescript // background/index.ts (required for messaging) export {} // background/messages/ping.ts import type { PlasmoMessaging } from "@plasmohq/messaging" export type RequestBody = { id: number } export type ResponseBody = { message: string timestamp: number } const handler: PlasmoMessaging.MessageHandler = async (req, res) => { const { id } = req.body // Perform API call without CORS restrictions const apiData = await fetch(`https://api.example.com/item/${id}`) .then(r => r.json()) res.send({ message: `Fetched item ${id}: ${apiData.name}`, timestamp: Date.now() }) } export default handler ``` -------------------------------- ### Example `keys.json` with Browser Store Credentials Source: https://github.com/plasmohq/docs/blob/main/src/pages/framework/workflows/submit.mdx An example of a `keys.json` file containing specific credentials for Chrome and Edge browser stores. This includes client IDs, refresh tokens, and other necessary authentication details. Ensure these are kept secure as repository secrets. ```json { "$schema": "https://raw.githubusercontent.com/plasmo-corp/bpp/v3/keys.schema.json", "chrome": { "clientId": "123", "refreshToken": "789", "extId": "abcd", "clientSecret": "efgh" }, "edge": { "clientId": "aaaaaaa-aaaa-bbbb-cccc-dddddddddddd", "clientSecret": "abcdefg", "productId": "aaaaaaa-aaaa-bbbb-cccc-dddddddddddd", "accessTokenUrl": "https://login.microsoftonline.com/aaaaaaa-aaaa-bbbb-cccc-dddddddddddd/oauth2/v2.0/token" } } ``` -------------------------------- ### Install Plasmo CLI (Bash) Source: https://github.com/plasmohq/docs/blob/main/src/pages/quickstarts/migrate-to-plasmo.mdx This command installs the Plasmo CLI, which is the primary tool for managing and building browser extensions with Plasmo. It bundles a compiler, bundler, development server, and packager tailored for browser extensions. ```bash pnpm install plasmo ``` -------------------------------- ### Install TailwindCSS and Dependencies Source: https://context7.com/plasmohq/docs/llms.txt Provides the necessary commands to install TailwindCSS, PostCSS, and Autoprefixer as development dependencies for styling your Plasmo extension. It also initializes TailwindCSS configuration files. ```bash pnpm i -D tailwindcss@3 postcss autoprefixer npx tailwindcss init -p ``` -------------------------------- ### Install @plasmohq/messaging Package Source: https://github.com/plasmohq/docs/blob/main/src/pages/framework/messaging.mdx This command installs the necessary `@plasmohq/messaging` library using the pnpm package manager. This is the first step in setting up the messaging API for your extension. ```bash pnpm install @plasmohq/messaging ``` -------------------------------- ### Install @plasmohq/storage Source: https://github.com/plasmohq/docs/blob/main/src/pages/framework/storage.mdx Installs the @plasmohq/storage library using pnpm. This library provides utilities for browser extension storage. ```bash pnpm install @plasmohq/storage ``` -------------------------------- ### Set up Supabase Environment Variables Source: https://github.com/plasmohq/docs/blob/main/src/pages/quickstarts/with-supabase.mdx Defines necessary Supabase URL and API Key in the .env file. These are public variables prefixed with PLASMO_PUBLIC. ```ini PLASMO_PUBLIC_SUPABASE_URL="CHANGE ME" PLASMO_PUBLIC_SUPABASE_KEY="CHANGE ME" ``` -------------------------------- ### Initiate Stripe Payment Link and OAuth Flow (TypeScript) Source: https://github.com/plasmohq/docs/blob/main/src/pages/quickstarts/with-stripe.mdx This snippet shows how to initiate a Stripe payment link while also invoking the Chrome identity API to get an OAuth token. It pre-fills the user's email and client reference ID into the Stripe link and opens it in a new tab. Requires `userInfo` to be available. ```tsx ``` -------------------------------- ### Configure Web Accessible Resources Source: https://github.com/plasmohq/docs/blob/main/src/pages/quickstarts/with-supabase.mdx Defines 'options.html' as a web-accessible resource, allowing it to be accessed by other origins, and specifies the extension ID that can access it. ```json "web_accessible_resources": [ { "resources": [ "options.html" ], "matches": [ "" ], "extension_ids": [ "$CRX_ID" ] } ] ``` -------------------------------- ### Start Plasmo Development Server Source: https://github.com/plasmohq/docs/blob/main/src/pages/framework/index.mdx This command starts the Plasmo development server. It enables live-reloading and React Hot Module Replacement (HMR), automatically rebuilding the extension and reloading it in the browser upon file changes. ```shell pnpm dev ``` -------------------------------- ### React Sign Up Prompt Link Source: https://github.com/plasmohq/docs/blob/main/src/pages/quickstarts/with-firebase-authentication.mdx This component provides a prompt for users who don't have an account, offering a link to sign up. It's commonly found at the bottom of login forms to guide users through the registration process. The link is styled to be visually distinct. ```jsx

Don’t have an account yet?{" "} ``` -------------------------------- ### Configure Extension ID and Key Source: https://github.com/plasmohq/docs/blob/main/src/pages/quickstarts/with-supabase.mdx Sets up environment variables for the extension ID and public key. The public key is used in the package.json manifest. ```ini CRX_ID="Replace with the value of CRX ID from Itero KeyPair tool" CRX_KEY="Replace with the value of Public Key from Itero KeyPair tool" ``` -------------------------------- ### Use Experimental Plasmo Version (package.json) Source: https://github.com/plasmohq/docs/blob/main/src/pages/framework/workflows/faq.mdx This snippet demonstrates how to configure your project to use the experimental 'lab' version of the Plasmo framework by modifying the 'package.json' file. Ensure you have a package manager like pnpm installed to run the subsequent installation command. ```json { "dependencies": { "plasmo": "lab" } } ``` -------------------------------- ### Configure Environment Variables for Stripe Source: https://github.com/plasmohq/docs/blob/main/src/pages/quickstarts/with-stripe.mdx Set up development environment variables for your Stripe payment link and private API key. These variables are crucial for integrating Stripe functionality into your Plasmo project. ```ini PLASMO_PUBLIC_STRIPE_LINK=https://buy.stripe.com/test_XXXXXXXX STRIPE_PRIVATE_API_KEY=sk_test_xxxxxxxxxxxxxxxxxxxxxx ``` -------------------------------- ### Project Dependencies and Scripts (JSON) Source: https://github.com/plasmohq/docs/blob/main/src/pages/quickstarts/with-stripe.mdx This JSON snippet defines the scripts and dependencies for a project integrating Next.js with Plasmo. It includes development and build scripts for both Plasmo and Next.js, as well as essential libraries like `next`, `google-auth-library`, `swr`, `stripe`, and `@plasmohq/rps`. ```json { "scripts": { "start": "next start", "dev": "run-p dev:* "dev:plasmo": "plasmo dev", "dev:next": "next dev --port 8472", "build": "run-p build:* "build:plasmo": "plasmo build", "build:next": "next build" }, ... "dependencies": { ... "next": "12.1.6", "google-auth-library": "8.0.2", "swr": "1.3.0", "stripe": "9.8.0" }, "devDependencies": { ... "@plasmohq/rps": "1.3.4" } } ``` -------------------------------- ### Environment Variable Setup for Google Analytics Source: https://github.com/plasmohq/docs/blob/main/src/pages/quickstarts/with-google-analytics.mdx Sets up the Google Analytics Measurement ID using environment variables. The `.env.local` file stores the public GTag ID, while `index.d.ts` provides TypeScript definitions for `process.env.PLASMO_PUBLIC_GTAG_ID` and global `window.gtag` and `window.dataLayer` objects, essential for type safety. ```ini PLASMO_PUBLIC_GTAG_ID= ``` ```ts declare namespace NodeJS { interface ProcessEnv { PLASMO_PUBLIC_GTAG_ID?: string } } interface Window { dataLayer: Array gtag: (a: string, b: any, c?: any) => void } ``` -------------------------------- ### Create User Info React Context Provider Source: https://github.com/plasmohq/docs/blob/main/src/pages/quickstarts/with-stripe.mdx Implements a React context provider using `puro` to fetch and manage user profile information via `chrome.identity.getProfileUserInfo`. It includes state management for the user data and a hook to access it. ```tsx import { createProvider } from "puro" import { useContext, useEffect, useState } from "react" const useUserInfoProvider = () => { const [userInfo, setUserInfo] = useState(null) useEffect(() => { chrome.identity.getProfileUserInfo((data) => { if (data.email && data.id) { setUserInfo(data) } }) }, []) return userInfo } const { BaseContext, Provider } = createProvider(useUserInfoProvider) export const useUserInfo = () => useContext(BaseContext) export const UserInfoProvider = Provider ``` -------------------------------- ### Configure Development Environment Variables Source: https://github.com/plasmohq/docs/blob/main/src/pages/quickstarts/with-stripe.mdx Sets the `CRX_PUBLIC_KEY` environment variable in `.env.development` to store the generated public key. This variable is referenced in the `package.json` manifest. ```env ... CRX_PUBLIC_KEY=v47xxx ``` -------------------------------- ### Initialize Supabase Client in TypeScript Source: https://github.com/plasmohq/docs/blob/main/src/pages/quickstarts/with-supabase.mdx Initializes the Supabase client using environment variables and Plasmo's Storage for session persistence. It requires the '@supabase/supabase-js' and '@plasmohq/storage' packages. ```typescript import { createClient } from "@supabase/supabase-js" import { Storage } from "@plasmohq/storage" const storage = new Storage({ area: "local" }) export const supabase = createClient( process.env.PLASMO_PUBLIC_SUPABASE_URL, process.env.PLASMO_PUBLIC_SUPABASE_KEY, { auth: { storage, autoRefreshToken: true, persistSession: true, detectSessionInUrl: true } } ) ``` -------------------------------- ### Configure Manifest Key Source: https://github.com/plasmohq/docs/blob/main/src/pages/quickstarts/with-supabase.mdx References the CRX_KEY environment variable within the package.json manifest to specify the extension's public key. ```json "manifest": { "host_permissions": [ "https://*/*" ], "key": "$CRX_KEY" } ``` -------------------------------- ### Define PostCSS Configuration (JavaScript) Source: https://github.com/plasmohq/docs/blob/main/src/pages/quickstarts/with-tailwindcss.mdx Configuration file for PostCSS, enabling Tailwind CSS and Autoprefixer. It specifies the plugins to be used in the PostCSS build process. Ensure the filename is `.js`, not `.cjs`, to avoid parsing issues. ```javascript /** * @type {import('postcss').ProcessOptions} */ module.exports = { plugins: { tailwindcss: {}, autoprefixer: {} } } ``` -------------------------------- ### Add Identity Permissions to Manifest Source: https://github.com/plasmohq/docs/blob/main/src/pages/quickstarts/with-stripe.mdx Enable the 'identity' and 'identity.email' permissions in your extension's manifest file. This allows your extension to use the Chrome Identity API for authentication and retrieving user email. ```json { "manifest": { "permissions": ["identity", "identity.email"] } } ``` -------------------------------- ### Generate Private Key using OpenSSL Source: https://github.com/plasmohq/docs/blob/main/src/pages/quickstarts/with-stripe.mdx Generates a 2048-bit RSA private key using OpenSSL and saves it in PKCS#8 format. This key is essential for pinning the extension ID during development. ```sh openssl genrsa 2048 | openssl pkcs8 -topk8 -nocrypt -out key.pem ``` -------------------------------- ### Configure OAuth2 Client ID in package.json Source: https://github.com/plasmohq/docs/blob/main/src/pages/quickstarts/with-stripe.mdx Defines the `oauth2` configuration in the `manifest` override of `package.json`, including the `client_id` sourced from the `$OAUTH_CLIENT_ID` environment variable and necessary scopes. ```json { ... "manifest": { ... "oauth2": { "client_id": "$OAUTH_CLIENT_ID", "scopes": [ "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile" ] } } } ``` -------------------------------- ### Generate Tailwind CSS Config File (Bash) Source: https://github.com/plasmohq/docs/blob/main/src/pages/quickstarts/with-tailwindcss.mdx Command to generate the `tailwind.config.js` and `postcss.config.js` files. The `-p` flag ensures that `postcss.config.js` is also generated. ```bash npx tailwindcss init -p ``` -------------------------------- ### Set Fixed Extension Key in package.json Source: https://github.com/plasmohq/docs/blob/main/src/pages/quickstarts/with-stripe.mdx Specifies the `key` field within the `manifest` override in `package.json`, using the environment variable `$CRX_PUBLIC_KEY`. This ensures a fixed extension ID for development. ```json { "manifest": { ... "key": "$CRX_PUBLIC_KEY" } } ``` -------------------------------- ### Configure Tailwind CSS (JavaScript) Source: https://github.com/plasmohq/docs/blob/main/src/pages/quickstarts/with-tailwindcss.mdx Configuration file for Tailwind CSS. It defines the build mode, dark mode strategy, content sources to scan for classes, and any custom plugins. The `mode: "jit"` enables the Just-In-Time engine for faster builds. ```javascript /** @type {import('tailwindcss').Config} */ module.exports = { mode: "jit", darkMode: "class", content: ["./**/*.tsx"], plugins: [] } ``` -------------------------------- ### Build Command with Environment Flags Source: https://github.com/plasmohq/docs/blob/main/src/pages/framework/env.mdx Example of a Plasmo build command specifying a target and tag, which influences which environment variable files are loaded. ```sh plasmo build --target=safari-mv3 --tag=alpha ``` -------------------------------- ### Configure OAuth Client ID in .env.development Source: https://github.com/plasmohq/docs/blob/main/src/pages/quickstarts/with-stripe.mdx Stores the obtained OAuth2 client ID in the `OAUTH_CLIENT_ID` environment variable within `.env.development`. This ID is used for OAuth2 authentication. ```env ... OAUTH_CLIENT_ID= ``` -------------------------------- ### Manifest Host Permissions (JSON) Source: https://github.com/plasmohq/docs/blob/main/src/pages/quickstarts/with-stripe.mdx This JSON snippet configures the `host_permissions` in the Plasmo extension's manifest file. It includes the base URI for the public API (obtained from an environment variable) and all HTTPS URIs, allowing the extension to communicate with the backend server. ```json { ... "manifest": { ... "host_permissions": [ "$PLASMO_PUBLIC_API_URI/*", "https://*/*" ] } } ``` -------------------------------- ### Basic Background Service Worker (JavaScript) Source: https://github.com/plasmohq/docs/blob/main/src/pages/quickstarts/migrate-to-plasmo.mdx A simple JavaScript example for a background service worker, typically used in non-Plasmo projects. It logs a message to the console when executed. ```js console.log("Hello from BGSW!") ``` -------------------------------- ### Plasmo Multiple Content Scripts (TS) Source: https://github.com/plasmohq/docs/blob/main/src/pages/quickstarts/migrate-to-plasmo.mdx Example of a content script within the `contents` directory that modifies the page's background color. If no configuration is explicitly exported, Plasmo applies a default configuration. ```typescript document.body.style.backgroundColor = "green" ``` -------------------------------- ### Start Plasmo Development Server Source: https://github.com/plasmohq/docs/blob/main/src/pages/framework/workflows/dev.mdx Initiates the development server for your browser extension. Plasmo creates a dev bundle and a live-reloading server, automatically updating the extension on file changes and reloading the browser. The development icon is grayscale and prefixed with 'DEV |'. ```sh pnpm dev # OR npm run dev # OR plasmo dev ``` -------------------------------- ### Generate Public Key from Private Key using OpenSSL Source: https://github.com/plasmohq/docs/blob/main/src/pages/quickstarts/with-stripe.mdx Derives the public key in DER format from a previously generated private key (`key.pem`) and then Base64 encodes it. This public key is used to fix the extension ID. ```sh openssl rsa -in key.pem -pubout -outform DER | openssl base64 -A ``` -------------------------------- ### Basic Content Script Setup (TypeScript) Source: https://github.com/plasmohq/docs/blob/main/src/pages/framework/content-scripts.mdx A minimal content script in TypeScript. It includes `export {}` to satisfy module requirements when no imports or exports are present, and a simple console log for demonstration. This is useful for basic script injection and debugging. ```typescript export {} console.log( "You may find that having is not so pleasing a thing as wanting. This is not logical, but it is often true." ) ``` -------------------------------- ### Add Root Styles with Tailwind Directives (CSS) Source: https://github.com/plasmohq/docs/blob/main/src/pages/quickstarts/with-tailwindcss.mdx The primary CSS file that includes Tailwind's base, components, and utilities directives. This file needs to be imported into your main application or component file to apply Tailwind styles. ```css @tailwind base; @tailwind components; @tailwind utilities; ``` -------------------------------- ### Environment Variable for API URI (INI) Source: https://github.com/plasmohq/docs/blob/main/src/pages/quickstarts/with-stripe.mdx This INI file sets the development environment variable `PLASMO_PUBLIC_API_URI` to specify the local development server's address. This is used by the extension to connect to the backend API during development. ```ini PLASMO_PUBLIC_API_URI=http://localhost:8472 ... ``` -------------------------------- ### Plasmo: Raw Import Scheme Example (TypeScript) Source: https://github.com/plasmohq/docs/blob/main/src/pages/framework/import.mdx Demonstrates how to use the `raw` import scheme in Plasmo to import an asset file. The scheme copies the file to the bundle with a content hash and returns a runtime URL. ```typescript import imageUrl from "raw:~/assets/image.png" console.log(imageUrl) // chrome-extension:///image..png ``` -------------------------------- ### Example Usage of External File Alias Source: https://github.com/plasmohq/docs/blob/main/src/pages/framework/customization/alias.mdx Demonstrates importing a module that has been aliased to a specific external file using the `package.json` alias configuration and a corresponding TypeScript declaration. ```tsx import { hello } from "some-cool-identifier/hello" ``` -------------------------------- ### Example Usage of Local TypeScript Aliases Source: https://github.com/plasmohq/docs/blob/main/src/pages/framework/customization/alias.mdx Demonstrates how to use the configured aliases for importing components from local directories. This simplifies component imports in your React/TypeScript code. ```tsx import { Button } from "@Components/button" import { Checkbox } from "@Components/checkbox" import { Header } from "@Components/header" import { Input } from "@Components/input" ``` -------------------------------- ### Basic Popup HTML Structure (HTML) Source: https://github.com/plasmohq/docs/blob/main/src/pages/quickstarts/migrate-to-plasmo.mdx This is a standard HTML file structure for a browser extension popup, often used in traditional setups. It includes a basic HTML document with a root element for a React application and links to a JavaScript file to render the component. ```html Popup

``` -------------------------------- ### Use User Info Context in Popup Component Source: https://github.com/plasmohq/docs/blob/main/src/pages/quickstarts/with-stripe.mdx Integrates the `UserInfoProvider` and `useUserInfo` hook into a React popup component (`popup.tsx`). It displays the user's email by consuming the context, demonstrating how to access shared state. ```tsx import { UserInfoProvider, useUserInfo } from "~core/user-info" const EmailShowcase = () => { const userInfo = useUserInfo() return (
Your email is: {userInfo?.email}
) } function IndexPopup() { return (

Welcome to your Plasmo Extension!

) } export default IndexPopup ``` -------------------------------- ### Basic Storage API Usage in TypeScript Source: https://github.com/plasmohq/docs/blob/main/src/pages/framework/storage.mdx Demonstrates basic usage of the Storage API for setting and getting string and object data. It handles JSON serialization/deserialization automatically for serializable data types. ```typescript import { Storage } from "@plasmohq/storage" const storage = new Storage() await storage.set("key", "value") const data = await storage.get("key") // "value" await storage.set("capt", { color: "red" }) const data2 = await storage.get("capt") // { color: "red" } ``` -------------------------------- ### Firebase Environment Variables (.env) Source: https://github.com/plasmohq/docs/blob/main/src/pages/quickstarts/with-firebase-authentication.mdx Defines environment variables for Firebase configuration. These variables, including API keys and project IDs, are essential for initializing the Firebase client app and should be populated from your Firebase Console. ```env PLASMO_PUBLIC_FIREBASE_CLIENT_ID="" PLASMO_PUBLIC_FIREBASE_PUBLIC_API_KEY="" PLASMO_PUBLIC_FIREBASE_AUTH_DOMAIN="" PLASMO_PUBLIC_FIREBASE_PROJECT_ID="" PLASMO_PUBLIC_FIREBASE_STORAGE_BUCKET="" PLASMO_PUBLIC_FIREBASE_MESSAGING_SENDER_ID="" PLASMO_PUBLIC_FIREBASE_APP_ID="" PLASMO_PUBLIC_FIREBASE_MEASUREMENT_ID="" ``` -------------------------------- ### Default Renderer: Using Inline or Overlay Container Source: https://github.com/plasmohq/docs/blob/main/src/pages/framework/content-scripts-ui/life-cycle.mdx This example demonstrates how to use the built-in `Inline Container` or `Overlay Container` provided by Plasmo. The `render` function is used to mount a component within these default containers. ```tsx import type { PlasmoRender } from "plasmo" const AnchorOverlay = ({ anchor }) => {anchor.innerText} export const render: PlasmoRender = ( { anchor, // the observed anchor, OR document.body. createRootContainer // This creates the default root container }, _, // Not used in this example OverlayCSUIContainer ) => { const rootContainer = await createRootContainer() const root = createRoot(rootContainer) // Any root root.render( // You must pass down an anchor to mount the default container. Here we pass the default one ) } ``` -------------------------------- ### Popup with SCSS Import (TypeScript) Source: https://github.com/plasmohq/docs/blob/main/src/pages/quickstarts/migrate-to-plasmo.mdx This TypeScript example illustrates how Plasmo supports CSS preprocessors like SCSS out-of-the-box. By importing an SCSS file directly into your React component, Plasmo's build process handles the compilation and injection of styles. ```typescript import Popup from "./core/popup" import "./popup.scss" export default Popup ``` -------------------------------- ### Background Service Worker with Imports (TypeScript) Source: https://github.com/plasmohq/docs/blob/main/src/pages/quickstarts/migrate-to-plasmo.mdx This TypeScript example demonstrates creating a background service worker in Plasmo using `background.ts`. It shows how to import modules like `bip39` and log messages, including the output of a generated mnemonic. ```ts import { generateMnemonic } from "bip39" console.log( "Live now; make now always the most precious time. Now will never come again." ) console.log(generateMnemonic()) ``` -------------------------------- ### Plasmo Content Script Configuration Source: https://context7.com/plasmohq/docs/llms.txt TypeScript code defining a content script for Plasmo. It specifies which URLs the script should run on (`matches`) and whether it should execute in all frames (`all_frames`). Includes an example of accessing page data. ```typescript // content.ts export {} import type { PlasmoCSConfig } from "plasmo" export const config: PlasmoCSConfig = { matches: ["https://*.github.com/*"], all_frames: true } console.log("Content script running on GitHub") // Scrape page data const repoName = document.querySelector('h1.repo-name')?.textContent console.log(`Repository: ${repoName}`) ``` -------------------------------- ### Custom Renderer: Dynamically creating a custom container Source: https://github.com/plasmohq/docs/blob/main/src/pages/framework/content-scripts-ui/life-cycle.mdx This example shows how to dynamically create a custom container element and insert it into the DOM before mounting the component. It overrides `getRootContainer` to handle element creation and insertion. ```tsx import type { PlasmoRender } from "plasmo" import { CustomContainer } from "~components/custom-container" const EngageOverlay = () => ENGAGE // This function overrides the default `createRootContainer` export const getRootContainer = ({ anchor, mountState }) => new Promise((resolve) => { const checkInterval = setInterval(() => { let { element, insertPosition } = anchor if (element) { const rootContainer = document.createElement("div") mountState.hostSet.add(rootContainer) mountState.hostMap.set(rootContainer, anchor) element.insertAdjacentElement(insertPosition, rootContainer) clearInterval(checkInterval) resolve(rootContainer) } }, 137) }) export const render: PlasmoRender = async ({ anchor, // the observed anchor, OR document.body. createRootContainer // This creates the default root container }) => { const rootContainer = await createRootContainer(anchor) const root = createRoot(rootContainer) // Any root root.render( ) } ``` -------------------------------- ### Create Custom Tab Page JavaScript Source: https://github.com/plasmohq/docs/blob/main/src/pages/quickstarts/migrate-to-plasmo.mdx JavaScript code for a custom tab page using React, demonstrating the setup for rendering a React component. This illustrates the client-side logic typically associated with custom HTML pages. ```javascript import { createRoot } from "react" import CustomPage from "./core/custom-page" const root = document.getElementById("root") createRoot(CustomPage).render() ``` -------------------------------- ### Create Plasmo Browser Extension Project Source: https://github.com/plasmohq/docs/blob/main/src/pages/framework/index.mdx This snippet shows how to initiate a new Plasmo browser extension project using different package managers. It sets up the basic project structure. ```shell pnpm create plasmo # OR yarn create plasmo # OR npm create plasmo ``` -------------------------------- ### Configure Redux Store with Persistence Source: https://github.com/plasmohq/docs/blob/main/src/pages/quickstarts/with-redux.mdx Sets up a Redux store using Redux Toolkit and integrates redux-persist for state persistence. It uses `redux-persist-webextension-storage` to persist the state in `chrome.storage` and includes middleware configuration to ignore specific Redux actions during serializable check. ```typescript import { configureStore } from "@reduxjs/toolkit" import { localStorage } from "redux-persist-webextension-storage" import { FLUSH, PAUSE, PERSIST, PURGE, REGISTER, REHYDRATE, RESYNC, persistReducer, persistStore } from "@plasmohq/redux-persist" import { Storage } from "@plasmohq/storage" import counterSlice from "~counter-slice" const rootReducer = counterSlice const persistConfig = { key: "root", version: 1, storage: localStorage } const persistedReducer = persistReducer(persistConfig, rootReducer) export const store = configureStore({ reducer: persistedReducer, middleware: (getDefaultMiddleware) => getDefaultMiddleware({ serializableCheck: { ignoredActions: [ FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER, RESYNC ] } }) }) export const persistor = persistStore(store) // This is what makes Redux sync properly with multiple pages // Open your extension's options page and popup to see it in action new Storage().watch({ [`persist:${persistConfig.key}`]: () => { persistor.resync() } }) ``` -------------------------------- ### Initialize Firebase Client App (TypeScript) Source: https://github.com/plasmohq/docs/blob/main/src/pages/quickstarts/with-firebase-authentication.mdx Initializes a singleton instance of the Firebase client application. It checks for existing app instances to prevent re-initialization during hot-reloads and exports essential Firebase services like auth, firestore, and storage. ```typescript // src/firebase/firebaseClient.ts import { getApps, initializeApp } from "firebase/app" import { GoogleAuthProvider, getAuth } from "firebase/auth" import { getFirestore } from "firebase/firestore" import { getStorage } from "firebase/storage" const clientCredentials = { apiKey: process.env.PLASMO_PUBLIC_FIREBASE_PUBLIC_API_KEY, authDomain: process.env.PLASMO_PUBLIC_FIREBASE_AUTH_DOMAIN, projectId: process.env.PLASMO_PUBLIC_FIREBASE_PROJECT_ID, storageBucket: process.env.PLASMO_PUBLIC_FIREBASE_STORAGE_BUCKET, messagingSenderId: process.env.PLASMO_PUBLIC_FIREBASE_MESSAGING_SENDER_ID, appId: process.env.PLASMO_PUBLIC_FIREBASE_APP_ID, measurementId: process.env.PLASMO_PUBLIC_FIREBASE_MEASUREMENT_ID } let firebase_app // Check if firebase app is already initialized to avoid creating new app on hot-reloads if (!getApps().length) { firebase_app = initializeApp(clientCredentials) } else { firebase_app = getApps()[0] } export const storage = getStorage(firebase_app) export const auth = getAuth(firebase_app) export const db = getFirestore(firebase_app) export const googleAuth = new GoogleAuthProvider() export default firebase_app ``` -------------------------------- ### Use Tailwind CSS in Extension Popup (TypeScript/React) Source: https://github.com/plasmohq/docs/blob/main/src/pages/quickstarts/with-tailwindcss.mdx Example of a React component for a Plasmo extension popup page using Tailwind CSS classes for styling. It imports the global styles and applies Tailwind classes directly to HTML elements. ```tsx import { useReducer } from "react" import "./style.css" function IndexPopup() { const [count, increase] = useReducer((c) => c + 1, 0) return ( ) } export default IndexPopup ``` -------------------------------- ### React Supabase Authentication Component Source: https://github.com/plasmohq/docs/blob/main/src/pages/quickstarts/with-supabase.mdx This React component demonstrates Supabase authentication within a Plasmo extension. It handles user login, signup, and OAuth flows using Supabase's client library and `@plasmohq/storage` for session persistence. It displays user information or authentication forms based on the login state. ```tsx import type { Provider, User } from "@supabase/supabase-js" import { useEffect, useState } from "react" import { Storage } from "@plasmohq/storage" import { useStorage } from "@plasmohq/storage/hook" import { supabase } from "~core/supabase" function IndexOptions() { const [user, setUser] = useStorage({ key: "user", instance: new Storage({ area: "local" }) }) const [username, setUsername] = useState("") const [password, setPassword] = useState("") useEffect(() => { async function init() { const { data, error } = await supabase.auth.getSession() if (error) { console.error(error) return } if (!!data.session) { setUser(data.session.user) } } init() }, []) const handleEmailLogin = async ( type: "LOGIN" | "SIGNUP", username: string, password: string ) => { try { const { error, data: { user } } = type === "LOGIN" ? await supabase.auth.signInWithPassword({ email: username, password }) : await supabase.auth.signUp({ email: username, password }) if (error) { alert("Error with auth: " + error.message) } else if (!user) { alert("Signup successful, confirmation mail should be sent soon!") } else { setUser(user) } } catch (error) { console.log("error", error) alert(error.error_description || error) } } const handleOAuthLogin = async (provider: Provider, scopes = "email") => { await supabase.auth.signInWithOAuth({ provider, options: { scopes, redirectTo: location.href } }) } return (
{user && ( <>

{user.email} - {user.id}

)} {!user && ( <> setUsername(e.target.value)} /> setPassword(e.target.value)} /> )}
) } export default IndexOptions ``` -------------------------------- ### Use Environment Variables in Locale Messages (JSON) Source: https://github.com/plasmohq/docs/blob/main/src/pages/framework/locales.mdx Allows dynamic content within locale messages by utilizing environment variables. The example shows how `$PLASMO_PUBLIC_QUOTE_AUTHOR` can be injected into the `popup` message. This requires a corresponding `.env` file to define the variable. ```json { ... "popup": { "message": "Logic is the beginning of wisdom, not the end. - $PLASMO_PUBLIC_QUOTE_AUTHOR", "description": "Popup message." } } ``` -------------------------------- ### Check Subscription API Call with SWR (TypeScript) Source: https://github.com/plasmohq/docs/blob/main/src/pages/quickstarts/with-stripe.mdx This TypeScript code demonstrates how to use the `useSWR` hook to fetch subscription status from a backend API. It defines a data fetching function `callAPI` and uses it to revalidate the `/api/check-subscription` endpoint, conditionally rendering UI based on the subscription status. ```tsx import useSWR from "swr" import { callAPI } from "~core/premium-api" ... const { data, error } = useSWR<{ active: boolean }>( "/api/check-subscription", callAPI ) if (!!error || !data?.active) { // No active subscription, show pay button } // Has active subscription, show premium feature button ``` -------------------------------- ### Invoke Premium Feature API Call (TypeScript) Source: https://github.com/plasmohq/docs/blob/main/src/pages/quickstarts/with-stripe.mdx This TypeScript snippet shows how to invoke a premium feature by making a POST request to the `/api/premium-feature` endpoint using a `callAPI` helper function. Upon successful response, it displays the feature's code via an alert. ```tsx ``` -------------------------------- ### Build and Package Browser Extension with Plasmo CLI Source: https://github.com/plasmohq/docs/blob/main/src/pages/itero/test-bed.mdx These bash commands are used to build and package a browser extension using the Plasmo Framework. 'pnpm build' compiles the extension's source code, and 'pnpm package' creates a distributable zip file ready for deployment or testing. ```bash pnpm build pnpm package ``` -------------------------------- ### Inject Tailwind Styles into Content Scripts UI (TypeScript/React) Source: https://github.com/plasmohq/docs/blob/main/src/pages/quickstarts/with-tailwindcss.mdx Example of how to use Tailwind CSS within a Plasmo Content Scripts UI (CSUI). It imports the CSS as text and uses the `getStyle` method to inject it into the CSUI's shadow DOM. ```tsx import cssText from "data-text:~style.css" import { useReducer } from "react" export const getStyle = () => { const style = document.createElement("style") style.textContent = cssText return style } const PlasmoOverlay = () => { const [count, increase] = useReducer((c) => c + 1, 0) return ( ) } export default PlasmoOverlay ``` -------------------------------- ### Basic TailwindCSS Styling for Extension Pages Source: https://context7.com/plasmohq/docs/llms.txt An example of a React component for a Plasmo extension popup using TailwindCSS utility classes for styling buttons and text. It includes basic styling for background, padding, text color, and hover effects. ```tsx // popup.tsx - Use in extension pages import { useReducer } from "react" import "./style.css" function IndexPopup() { const [count, increase] = useReducer((c) => c + 1, 0) return (
) } export default IndexPopup ``` -------------------------------- ### Inject React Component with Plasmo CSUI Source: https://github.com/plasmohq/docs/blob/main/src/pages/framework/content-scripts-ui.mdx Demonstrates how to create and export a default React component to be injected into a web page using Plasmo's Content Scripts UI. This setup requires a `content.tsx` file. ```tsx const CustomButton = () => { return } export default CustomButton ``` -------------------------------- ### Build Production Bundle (npm/pnpm) Source: https://github.com/plasmohq/docs/blob/main/src/pages/framework/workflows/build.mdx Commands to create a production bundle for distribution. These commands initiate the build process for your browser extension. ```shell pnpm build # OR npm run build ``` -------------------------------- ### Implementing Google Analytics in a React Component Source: https://github.com/plasmohq/docs/blob/main/src/pages/quickstarts/with-google-analytics.mdx Integrates the Google Analytics gtag tracking script into a React component for a browser extension. It dynamically loads the gtag script and initializes the data layer and gtag function within the component's lifecycle using `useEffect`. This approach bypasses MV3 limitations by bundling the script at build time. ```tsx import "https://www.googletagmanager.com/gtag/js?id=$PLASMO_PUBLIC_GTAG_ID" import { useEffect, useState } from "react" function IndexPopup() { const [data, setData] = useState("") useEffect(() => { window.dataLayer = window.dataLayer || [] window.gtag = function gtag() { window.dataLayer.push(arguments) // eslint-disable-line } window.gtag("js", new Date()) window.gtag("config", process.env.PLASMO_PUBLIC_GTAG_ID, { page_path: "/popup", debug_mode: true }) window.gtag("event", "login", { method: "TEST" }) }, []) return (

Welcome to your Plasmo Extension!

setData(e.target.value)} value={data} />
) } export default IndexPopup ``` -------------------------------- ### Build Plasmo Production Bundles Source: https://context7.com/plasmohq/docs/llms.txt Commands for creating optimized production builds of Plasmo browser extensions. Supports options for zip packaging, browser/manifest targeting, custom build tags, source maps, and optimization flags. ```bash # Standard production build pnpm build # Build with zip package ready for store submission pnpm build --zip # Target specific browser and manifest version plasmo build --target=firefox-mv2 # Output: build/firefox-mv2-prod/ # Custom build tag with environment support plasmo build --tag=staging # Output: build/chrome-mv3-staging/ # Uses .env.staging if available # Development build with source maps and bundle analysis plasmo build --source-maps --bundle-buddy # Optimization flags plasmo build --no-minify --hoist ``` -------------------------------- ### React Login Link Source: https://github.com/plasmohq/docs/blob/main/src/pages/quickstarts/with-firebase-authentication.mdx This component provides a link to navigate to the login section, typically used after a user decides they already have an account. It uses `onClick` to conditionally render the login form and applies styling to make it appear as a clickable text link. ```jsx

Already have an account?{" "}

``` -------------------------------- ### Adapt Tailwind Root Styles for CSUI Shadow DOM (TypeScript/React) Source: https://github.com/plasmohq/docs/blob/main/src/pages/quickstarts/with-tailwindcss.mdx A specific implementation for Content Scripts UI (CSUI) that modifies Tailwind CSS to work correctly within a shadow DOM. It replaces the `:root` selector with `:host(plasmo-csui)` to ensure CSS variables are scoped properly, which is crucial for libraries like DaisyUI. ```tsx import cssText from "data-text:~style.css" export const getStyle = () => { const style = document.createElement("style") style.textContent = cssText.replaceAll(':root', ':host(plasmo-csui)'); return style } ``` -------------------------------- ### Create Plasmo Browser Extension Project Source: https://context7.com/plasmohq/docs/llms.txt Command-line interface commands to initiate a new Plasmo browser extension project. It supports different package managers (pnpm, yarn, npm) and an option to include Tailwind CSS. ```bash pnpm create plasmo # OR yarn create plasmo # OR npm create plasmo # With TailwindCSS pre-configured pnpm create plasmo --with-tailwindcss ```