plasmo

为 Plasmo 框架提供专家级指导,该框架用于使用 React、TypeScript 和现代工具构建浏览器扩展。帮助开发者创建 Chrome 和 Firefox 扩展,包括内容脚本、后台工作线程、弹出式 UI 和消息传递,并支持热重载与零 Webpack 配置的工作流相关指导。

仓库最近推送
GitHub Stars
219
Forks
38
Issues / PRs
7

安装方式

先用 Prompt 核对来源与依赖。也可下载安装包。

用 AI 助手安装

复制提示词,让助手先核对固定版本和依赖。

查看 Prompt收起 Prompt
先检查当前 Agent 是否已安装 SkillPI Skill Finder。如果尚未安装,请按官方仓库的说明安装并启用:https://github.com/Findskills/skillpi。然后使用 Skill Finder 打开此 SkillPI 详情页并定位 "plasmo":https://skillpi.com/zh/skills/deepskill-479322dce5e6f33c87c45ec80581aa821e215aabc825a1554a1bd7f87900e7ac。安装前核对上游来源和版本:https://github.com/TerminalSkills/skills。来源不一致时停止并说明差异。核对通过后,用 Skill Finder 安装目标 Skill,并报告安装路径和来源版本。

来源与配置

github.com

配置方式待核实

请查看原始来源中的适用工具、依赖和权限要求。

安装实测待补充

为 Plasmo 框架提供专家级指导,该框架用于使用 React、TypeScript 和现代工具构建浏览器扩展。帮助开发者创建 Chrome 和 Firefox 扩展,包括内容脚本、后台工作线程、弹出式 UI 和消息传递,并支持热重载与零 Webpack 配置的工作流相关指导。

0 下载

介绍来源: third_party · TerminalSkills · 1.0.0 参考来源

SkillPi 解读

能完成的任务
翻译待完成,请参阅来源文档。
软件、账号及付费要求
翻译待完成,请参阅来源文档。
实测状态
未测试

文件浏览

在原站浏览文件 ↗

原始 SKILL.md

打开原文 ↗
Frontmatter
name: plasmo
description: Expert guidance for Plasmo, the framework for building browser extensions with React, TypeScript, and modern tooling. Helps developers create Chrome and Firefox extensions with content scripts, background workers, popup UIs, and messaging — all with hot reload and zero webpack config.
license: Apache-2.0
compatibility: No special requirements
metadata:
  author: terminal-skills
  version: 1.0.0
  category: development
  tags:
  - chrome-extension
  - browser
  - react
  - typescript
  - manifest-v3

Plasmo — Browser Extension Framework

Overview

Plasmo, the framework for building browser extensions with React, TypeScript, and modern tooling. Helps developers create Chrome and Firefox extensions with content scripts, background workers, popup UIs, and messaging — all with hot reload and zero webpack config.

Instructions

Project Setup

Create a new extension with Plasmo CLI:

# Create a new extension project
pnpm create plasmo my-extension
# Or with a specific template
pnpm create plasmo --with-tailwindcss my-extension

# Development with hot reload
pnpm dev
# Build for production
pnpm build
# Package for Chrome Web Store
pnpm package

Popup UI

Build the extension popup as a React component:

// src/popup.tsx — Main popup UI (click the extension icon)
import { useState, useEffect } from "react";
import { Storage } from "@plasmohq/storage";

const storage = new Storage();

function IndexPopup() {
  const [savedCount, setSavedCount] = useState(0);
  const [isEnabled, setIsEnabled] = useState(true);

  useEffect(() => {
    // Load state from extension storage (persists across sessions)
    storage.get<number>("savedCount").then((count) => setSavedCount(count ?? 0));
    storage.get<boolean>("isEnabled").then((enabled) => setIsEnabled(enabled ?? true));
  }, []);

  const toggleExtension = async () => {
    const newState = !isEnabled;
    setIsEnabled(newState);
    await storage.set("isEnabled", newState);
    // Notify content scripts about the state change
    const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
    if (tabs[0]?.id) {
      chrome.tabs.sendMessage(tabs[0].id, { type: "TOGGLE", enabled: newState });
    }
  };

  return (
    <div style={{ padding: 16, width: 320 }}>
      <h2>My Extension</h2>
      <p>Saved items: {savedCount}</p>
      <button onClick={toggleExtension}>
        {isEnabled ? "🟢 Enabled" : "🔴 Disabled"}
      </button>
    </div>
  );
}

export default IndexPopup;

Content Scripts

Inject UI and logic into web pages:

// src/contents/overlay.tsx — Content script that renders a React component on any page
import type { PlasmoCSConfig, PlasmoGetOverlayAnchor } from "plasmo";
import { useState } from "react";

// Configure which pages this content script runs on
export const config: PlasmoCSConfig = {
  matches: ["https://github.com/*"],           // Only on GitHub
  css: ["contents/overlay.css"],                // Optional custom CSS
};

// Anchor the overlay to a specific DOM element (optional)
export const getOverlayAnchor: PlasmoGetOverlayAnchor = async () => {
  return document.querySelector(".repository-content");
};

// The React component renders as an overlay on the page
function GitHubOverlay() {
  const [isOpen, setIsOpen] = useState(false);

  return (
    <div className="plasmo-overlay">
      <button onClick={() => setIsOpen(!isOpen)}>
        📋 Quick Actions
      </button>
      {isOpen && (
        <div className="plasmo-panel">
          <button onClick={() => copyRepoInfo()}>Copy repo info</button>
          <button onClick={() => analyzeReadme()}>Analyze README</button>
        </div>
      )}
    </div>
  );
}

async function copyRepoInfo() {
  const title = document.querySelector("[itemprop='name'] a")?.textContent?.trim();
  const desc = document.querySelector("[itemprop='about']")?.textContent?.trim();
  const stars = document.querySelector("#repo-stars-counter-star")?.textContent?.trim();
  await navigator.clipboard.writeText(`${title}: ${desc} (⭐ ${stars})`);
}

export default GitHubOverlay;

Background Service Worker

Handle long-running tasks, alarms, and cross-tab communication:

// src/background.ts — Background service worker (Manifest V3)
import { Storage } from "@plasmohq/storage";

const storage = new Storage();

// Listen for messages from content scripts and popup
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  switch (message.type) {
    case "SAVE_ITEM":
      handleSaveItem(message.data).then(sendResponse);
      return true;     // Keep the message channel open for async response

    case "GET_STATS":
      getStats().then(sendResponse);
      return true;
  }
});

async function handleSaveItem(data: { url: string; title: string; content: string }) {
  const items = (await storage.get<any[]>("savedItems")) ?? [];
  items.push({ ...data, savedAt: Date.now() });
  await storage.set("savedItems", items);

  // Update badge count
  const count = items.length;
  chrome.action.setBadgeText({ text: count > 0 ? String(count) : "" });
  chrome.action.setBadgeBackgroundColor({ color: "#6366f1" });

  return { success: true, count };
}

// Set up periodic tasks with alarms
chrome.alarms.create("sync-data", { periodInMinutes: 30 });

chrome.alarms.onAlarm.addListener(async (alarm) => {
  if (alarm.name === "sync-data") {
    const items = (await storage.get<any[]>("savedItems")) ?? [];
    if (items.length > 0) {
      // Sync to your backend API
      await fetch("https://api.example.com/sync", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ items }),
      });
    }
  }
});

// Context menu (right-click menu)
chrome.runtime.onInstalled.addListener(() => {
  chrome.contextMenus.create({
    id: "save-selection",
    title: "Save selection to My Extension",
    contexts: ["selection"],
  });
});

chrome.contextMenus.onClicked.addListener((info, tab) => {
  if (info.menuItemId === "save-selection" && info.selectionText) {
    handleSaveItem({
      url: tab?.url ?? "",
      title: tab?.title ?? "",
      content: info.selectionText,
    });
  }
});

Messaging Between Components

Type-safe communication between popup, content scripts, and background:

// src/messaging.ts — Type-safe messaging with Plasmo messaging API
import { sendToBackground, sendToContentScript } from "@plasmohq/messaging";

// Define message types
interface SaveRequest { url: string; title: string; }
interface SaveResponse { success: boolean; id: string; }

// From content script → background
async function saveFromContentScript(data: SaveRequest): Promise<SaveResponse> {
  return sendToBackground({
    name: "save-item",        // Maps to src/background/messages/save-item.ts
    body: data,
  });
}

// From popup → content script
async function highlightElements() {
  const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
  return sendToContentScript({
    name: "highlight",
    tabId: tabs[0].id!,
    body: { selector: "h1, h2, h3" },
  });
}
// src/background/messages/save-item.ts — Background message handler
import type { PlasmoMessaging } from "@plasmohq/messaging";

const handler: PlasmoMessaging.MessageHandler = async (req, res) => {
  const { url, title } = req.body;

  // Process the save request
  const id = crypto.randomUUID();
  await chrome.storage.local.set({ [id]: { url, title, savedAt: Date.now() } });

  res.send({ success: true, id });
};

export default handler;

Storage with React Hooks

Reactive storage that syncs across extension components:

// src/popup.tsx — Using storage hooks for reactive state
import { useStorage } from "@plasmohq/storage/hook";

function SettingsPopup() {
  // useStorage provides React state that persists and syncs
  // Changes in popup instantly reflect in content scripts and vice versa
  const [theme, setTheme] = useStorage<string>("theme", "light");
  const [apiKey, setApiKey] = useStorage<string>("apiKey", "");
  const [savedItems, setSavedItems] = useStorage<any[]>("savedItems", []);

  return (
    <div style={{ padding: 16, width: 350 }}>
      <h3>Settings</h3>

      <label>Theme</label>
      <select value={theme} onChange={(e) => setTheme(e.target.value)}>
        <option value="light">Light</option>
        <option value="dark">Dark</option>
      </select>

      <label>API Key</label>
      <input
        type="password"
        value={apiKey}
        onChange={(e) => setApiKey(e.target.value)}
        placeholder="Enter your API key"
      />

      <h3>Saved Items ({savedItems.length})</h3>
      <ul>
        {savedItems.slice(-5).map((item, i) => (
          <li key={i}>{item.title}</li>
        ))}
      </ul>
    </div>
  );
}

Options Page

Full-page settings interface:

// src/options.tsx — Extension options page (chrome-extension://id/options.html)
function OptionsPage() {
  const [settings, setSettings] = useStorage("settings", {
    autoSave: true,
    notifications: true,
    syncInterval: 30,
    excludedSites: [] as string[],
  });

  const updateSetting = (key: string, value: any) => {
    setSettings({ ...settings, [key]: value });
  };

  return (
    <div style={{ maxWidth: 600, margin: "40px auto", padding: 20 }}>
      <h1>Extension Settings</h1>
      <div>
        <label>
          <input type="checkbox" checked={settings.autoSave}
            onChange={(e) => updateSetting("autoSave", e.target.checked)} />
          Auto-save highlighted text
        </label>
      </div>
      <div>
        <label>Sync interval (minutes)</label>
        <input type="number" value={settings.syncInterval}
          onChange={(e) => updateSetting("syncInterval", parseInt(e.target.value))} />
      </div>
    </div>
  );
}

export default OptionsPage;

Installation

pnpm create plasmo my-extension
cd my-extension
pnpm dev     # Start dev server with hot reload

Examples

Example 1: Setting up Plasmo with a custom configuration

User request:

I just installed Plasmo. Help me configure it for my TypeScript + React workflow with my preferred keybindings.

The agent creates the configuration file with TypeScript-aware settings, configures relevant plugins/extensions for React development, sets up keyboard shortcuts matching the user's preferences, and verifies the setup works correctly.

Example 2: Extending Plasmo with custom functionality

User request:

I want to add a custom popup ui to Plasmo. How do I build one?

The agent scaffolds the extension/plugin project, implements the core functionality following Plasmo's API patterns, adds configuration options, and provides testing instructions to verify it works end-to-end.

Guidelines

  1. Manifest V3 by default — Plasmo generates MV3 manifests; service workers replace persistent background pages
  2. Use Plasmo storage over chrome.storage — @plasmohq/storage provides React hooks and cross-component sync
  3. Content script isolation — Plasmo uses Shadow DOM for content script UIs; your CSS won't leak into the page
  4. Minimize permissions — Request only the permissions you need in package.json under manifest.permissions
  5. Hot reload in dev — pnpm dev auto-reloads the extension on file changes; no manual refresh needed
  6. Type your messages — Use Plasmo's messaging API for type-safe communication between components
  7. Test across browsers — Build for both Chrome (pnpm build --target=chrome-mv3) and Firefox (--target=firefox-mv3)
  8. Bundle size matters — Extensions load on every page; keep content scripts small, lazy-load heavy logic

当前收录版本

1.0.0

核对来源版本 ↗

质量评测

满分100 · 来自 SkillPi LAB 实验室的评测报告。

场景价值85/100

亮点

  • 提供 Plasmo 框架的完整开发指南,涵盖浏览器扩展开发的核心模块
  • 内容详实,包含项目初始化、UI 构建、消息传递、存储管理等实用场景
触发精准95/100

亮点

  • 触发词精准覆盖 Plasmo、React、TypeScript、浏览器扩展等核心关键词
  • 边界清晰,无歧义或宽泛描述
结构规范90/100

待提升项

  • description 重复 原报告严重程度:轻微

    frontmatter 和 skill_body 中均包含 description,存在冗余

    改进建议:建议仅在 frontmatter 保留 description,skill_body 中可省略

亮点

  • 文档结构清晰,分模块讲解,代码示例完整且带注释
  • frontmatter 完整,包含 license、compatibility、metadata 等信息
执行可靠90/100

亮点

  • 所有代码示例均基于 Plasmo 官方 API,参数使用正确
  • 涵盖消息传递、存储同步、异常处理等关键可靠性设计
证据可验 (前四项均值)90/100

取前四项原始分值的算术平均,四舍五入取整。可通过收录报告核对各项评分与说明,运行记录需单独查证。

正文静态检测

100 / 100 · skillpi-20261123-no-r3-v1

正文未命中当前规则。

分数仅反映正文中的规则命中,供使用前参考。附件与运行行为不在此评分范围内。

权限与使用前检查

根据当前主文档自动整理,命中内容可能是示例或防护说明;不是实际权限声明,也未覆盖附件、外部依赖或运行行为。

文档引用的域名或地址

这些地址可能用于文档链接或示例,不是已批准的联网清单。使用前核对实际目的地及发送的数据。

  • api.example.com
  • github.com

本站展示提示不会授予权限。涉及文件改动、密钥、外部发送或费用时,仍由你使用的工具按需确认。

安全评级与访问范围

safe · 静态证据核验,不代表运行安全保证。

翻译待完成,请参阅来源文档。

使用前请由宿主核对并授权实际文件读写、外部服务和联网目的地;本站的核验不会授予任何运行权限。