cdp-live-edit-skill

Real-time edit tool using Chrome DevTools Protocol WebSocket to inject CSS/JS and modify the page DOM, allowing users to see page changes immediately.

Installation

Review the source and dependencies with a prompt. A package is available to download.

Install with an AI assistant

Copy the prompt so your assistant can review the pinned revision and dependencies first.

View promptHide prompt
Check whether SkillPI Skill Finder is installed for your current agent. If it is missing, install and enable it using the official instructions at https://github.com/Findskills/skillpi. Then use Skill Finder to locate and install "cdp-live-edit-skill" from this exact SkillPI detail page: https://skillpi.com/skills/deepskill-ef2a4c762611abe8b0edd2022ae851b42098eb7b00365ec070451024fa20cfcb. Verify the upstream source and version against https://skillhub.cn/skills/user_bda4ca23/cdp before installing. If they do not match, stop and report the mismatch. Report the installed path and source version.

Source and setup

skillhub.cn

Setup guidance pending

See the original source for supported tools, dependencies, and permissions.

Installation test pending

Real-time edit tool using Chrome DevTools Protocol WebSocket to inject CSS/JS and modify the page DOM, allowing users to see page changes immediately.

0 Downloads

Introduction source: third_party · user_bda4ca23 · 1.0.0 Reference

SkillPi interpretation

Tasks
Translation pending; see source documentation.
Inputs and outputs
bash node scripts/connect_cdp.js <targetId> 'JSON.stringify({title: document.title, url: location.href})' --save cat /tmp/cdp_last_result.json bash
Testing
Not tested

Browse files

Browse files at the source ↗

Original SKILL.md

Open original ↗
Frontmatter
name: cdp-live-edit
description: "通过 Chrome DevTools Protocol WebSocket 实时注入 CSS/JS 修改页面 DOM,用户立刻看到变化"
triggers:
  - "实时编辑"
  - "在线修改"
  - "eval修改"
  - "CDP编辑"
  - "页面实时修改"
version: 2.0.0
changelog:
  - "v2.0.0 — 2026-06-27: 达尔文优化: 新增配套脚本、多层错误处理、撤销机制、快捷命令、液态效果示例"
  - "v1.0.0 — 初始版本: 基本 CDP 连接与注入流程"

CDP 实时页面编辑 Skill

核心理念:通过 Chrome DevTools Protocol (CDP) WebSocket 在用户浏览器中实时注入 JS/CSS,用户立刻看到变化。 配合 xbrowser + Chrome headed 模式使用。 不需要修改源文件,所有修改在运行时生效。

架构

Darren的Chrome窗口 (headed)
        │
CDP :9222 (--remote-debugging-port=9222)
        │
 Agent ── Runtime.evaluate ──→ 页面实时变化
        │                         │
        └── 脚本工具层 ──────────← 修改/截图/撤销
             scripts/
               connect_cdp.js     ← 通用 CDP eval 连接脚本
               liquid_effect.js   ← 液态渐变动画注入
               check_chrome_cdp.sh ← 一键诊断

前置条件

1. 启动 Chrome CDP 模式

"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" \
  --remote-debugging-port=9222 \
  --remote-allow-origins=* \
  --user-data-dir=/tmp/chrome-cdp-persist \
  "http://目标页面URL"

参数说明:

  • --remote-debugging-port=9222:开启 CDP 端口
  • --remote-allow-origins=*:允许来自任意来源的 WebSocket 连接(Chrome ≥ 90 必需)
  • --user-data-dir=/tmp/chrome-cdp-persist:独立用户数据目录,避免影响默认 Chrome

2. 环境要求

组件 要求 验证
Node.js ≥ 14.x(含 ws 模块) node -e "require('ws'); console.log('OK')"
Chrome ≥ 90(推荐最新稳定版) curl -s http://127.0.0.1:9222/json/version \| python3 -c "import json,sys; print(json.load(sys.stdin).get('Browser','?'))"
curl 任意版本 用于页面列表查询

3. 一键诊断

bash scripts/check_chrome_cdp.sh
# 自动检查:端口连通性 → 浏览器版本 → 页面列表 → WebSocket 连接测试

快速开始(3 步流程)

Step 1: 查找目标页面

curl -s http://127.0.0.1:9222/json | python3 -c "
import json, sys
data = json.load(sys.stdin)
for i, page in enumerate(data):
    print(f'[{i}] {page.get(\"title\",\"(无标题)\")}')
    print(f'    URL: {page.get(\"url\",\"\")}')
    print(f'    ID:  {page.get(\"id\",\"\")}')
"

Step 2: 注入代码

方式 A — 使用脚本(推荐):

node scripts/connect_cdp.js <targetId> 'document.title = "新标题"'

方式 B — 使用 curl 轻量注入(无需 Node.js):

# 通过 CDP /json/new 获取 WebSocket URL
WS_URL=$(curl -s http://127.0.0.1:9222/json | python3 -c "
import json,sys
d=json.load(sys.stdin)
print('ws://127.0.0.1:9222/devtools/page/'+d[0]['id'])
")
# 使用 python3 websocket-client (需安装: pip install websocket-client)
python3 -c "
import websocket, json
ws = websocket.create_connection('$WS_URL', timeout=5)
ws.send(json.dumps({'id':1,'method':'Runtime.evaluate','params':{'expression':'document.title'}}))
print(ws.recv())
ws.close()
"

Step 3: 验证变化

页面会立即更新。也可以截图验证:

node scripts/connect_cdp.js <targetId> '
(async () => {
  const canvas = document.createElement("canvas");
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;
  const ctx = canvas.getContext("2d");
  ctx.drawWindow(window, 0, 0, canvas.width, canvas.height, "rgb(255,255,255)");
  // 简化方案:用 CDP Page.captureScreenshot
  return "截图指令已发送,详见完整截图方案";
})()
'

核心工作流

查找目标页面

# 快速模式:获取第一个页面的 ID
FIRST_ID=$(curl -s http://127.0.0.1:9222/json | python3 -c "import json,sys; print(json.load(sys.stdin)[0]['id'])")
echo "Target ID: $FIRST_ID"

通过 CDP WebSocket 注入 JS

基础 eval:

node scripts/connect_cdp.js <targetId> '你的JS代码'

获取返回值:

node scripts/connect_cdp.js <targetId> 'document.querySelector("h1").textContent'
# → 输出: 原标题文本

保存结果到文件:

node scripts/connect_cdp.js <targetId> 'JSON.stringify({title: document.title, url: location.href})' --save
cat /tmp/cdp_last_result.json

更复杂的操作(--keep-open 复用连接):

# 连接后保持打开,可用于多次 eval
node scripts/connect_cdp.js <targetId> 'document.title = "Step 1"' --keep-open

常见编辑操作(实用示例)

1. 修改标题

document.title = 'CDP Live Edit - ' + new Date().toLocaleString();

2. 调整颜色

// 修改单个元素
document.querySelector('.header').style.backgroundColor = '#1a1a2e';
document.querySelector('.header h1').style.color = '#e94560';

// 批量修改同类元素
document.querySelectorAll('.card').forEach((el, i) => {
  el.style.borderLeft = '4px solid hsl(' + (i * 30) + ', 80%, 50%)';
});

3. 修改字体

const fs = document.createElement('style');
fs.textContent = `
  @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&display=swap');
  body { font-family: 'Inter', sans-serif; }
  h1 { font-weight: 700; letter-spacing: -0.02em; }
`;
document.head.appendChild(fs);

4. 插入样式表

const s = document.createElement('style');
s.id = 'cdp-injected-style';
s.textContent = `
  body {
    background: linear-gradient(135deg, #0f0c29, #302b63, #24243e);
    color: #e0e0e0;
  }
  .content { max-width: 1200px; margin: 0 auto; padding: 2rem; }
  /* 更多样式规则... */
`;
document.head.appendChild(s);

5. 修改布局(间距 / 边距)

document.querySelectorAll('section').forEach(el => {
  el.style.padding = '4rem 2rem';
  el.style.margin = '2rem 0';
});
document.querySelector('main').style.display = 'flex';
document.querySelector('main').style.flexWrap = 'wrap';

6. 叠加液态渐变动画

// 完整示例见 scripts/liquid_effect.js
const liquidColors = ['#667eea', '#764ba2', '#f093fb', '#f5576c'];
const style = document.createElement('style');
style.id = 'cdp-liquid-style';
style.textContent = `
  body::before {
    content: '';
    position: fixed; top: 0; left: 0;
    width: 100%; height: 100%;
    z-index: -1; pointer-events: none;
    background: linear-gradient(135deg,
      ${liquidColors[0]} 0%, ${liquidColors[1]} 25%,
      ${liquidColors[2]} 50%, ${liquidColors[3]} 75%,
      ${liquidColors[0]} 100%);
    background-size: 400% 400%;
    animation: liquidFlow 8s ease infinite;
    opacity: 0.85;
  }
  @keyframes liquidFlow {
    0%   { background-position: 0% 50%; }
    25%  { background-position: 100% 0%; }
    50%  { background-position: 100% 100%; }
    75%  { background-position: 0% 100%; }
    100% { background-position: 0% 50%; }
  }
  /* 确保内容在动画层上方 */
  body > * { position: relative; z-index: 0; }
`;
document.head.appendChild(style);

// 注入: node scripts/connect_cdp.js <targetId> "$(cat scripts/liquid_effect.js)"

7. 修改隐藏/显示元素

// 隐藏元素
document.querySelector('.sidebar').style.display = 'none';

// 显示被隐藏的元素
document.querySelector('.hidden-banner').style.display = 'block';

// 切换淡入淡出
document.querySelector('.modal').style.opacity = '0';
document.querySelector('.modal').style.transition = 'opacity 0.3s';

8. 操作页面状态

// localStorage
localStorage.setItem('theme', 'dark');
localStorage.getItem('theme');

// sessionStorage
sessionStorage.setItem('temp_data', JSON.stringify({key: 'value'}));

// Cookie
document.cookie = "cdp_session=active; path=/; max-age=3600";

9. 获取页面快照(DOM)

// 保存原始 DOM 快照(用于撤销)
window.__cdp_snapshot = document.documentElement.outerHTML;
console.log('[CDP] 快照已保存 (' + window.__cdp_snapshot.length + ' 字符)');

// 恢复到快照
document.documentElement.innerHTML = window.__cdp_snapshot;
// 注意:此方式会重置所有运行时状态,更适合硬重置

10. 一键撤销所有修改

// 移除注入的样式
document.getElementById('cdp-injected-style')?.remove();
document.getElementById('cdp-liquid-style')?.remove();

// 移除内联样式(根据实际情况)
document.querySelectorAll('[style]').forEach(el => el.removeAttribute('style'));

// 如果有快照,硬恢复
if (window.__cdp_snapshot) {
  document.documentElement.innerHTML = window.__cdp_snapshot;
}

console.log('[CDP] 所有修改已撤销 ✓');

截图验证

完整截图方案(保存到本地文件):

(async () => {
  // 通过 CDP Page.captureScreenshot 截取页面
  // 注意:需要先通过 CDP 协议发送 Page.captureScreenshot 命令
  // 这里使用 Runtime.evaluate 先做简单检查
  return {
    viewport: {
      width: window.innerWidth,
      height: window.innerHeight,
      devicePixelRatio: window.devicePixelRatio
    },
    message: 'CDP screenshot ready — 使用 Page.captureScreenshot 在连接脚本中发送命令'
  };
})()

CDP 截图命令格式(通过 WebSocket):

{
  "id": 2,
  "method": "Page.captureScreenshot",
  "params": {
    "format": "png",
    "quality": 80,
    "fromSurface": true
  }
}

保存截图的 Node.js 脚本示例:

const ws = new WebSocket(wsUrl);
ws.on('open', () => {
  ws.send(JSON.stringify({id:1, method:'Page.captureScreenshot', params:{format:'png',quality:80,fromSurface:true}}));
});
ws.on('message', raw => {
  const resp = JSON.parse(raw.toString());
  if (resp.result && resp.result.data) {
    require('fs').writeFileSync('/tmp/cdp_screenshot.png', Buffer.from(resp.result.data, 'base64'));
    console.log('Screenshot saved to /tmp/cdp_screenshot.png');
  }
  ws.close();
});

多层级错误处理

第一层:前置检查

# 检查端口
curl -s -o /dev/null -w "%{http_code}" http://127.0.0.1:9222/json/version
# 输出应该是 200

# 检查是否有页面
curl -s http://127.0.0.1:9222/json | python3 -c "import json,sys; d=json.load(sys.stdin); assert len(d)>0, '没有打开的页面'"

第二层:运行时错误处理

所有的 connect_cdp.js 脚本调用都内置了:

  • 超时处理:默认 5s 超时,可通过 --timeout=ms 调整
  • CDP 错误响应:如 eval 语法错误会打印 CDP Error
  • 连接失败:Chrome 断开连接时打印清晰错误

第三层:异常状态恢复

// 页面挂起检测
const healthCheck = () => {
  try {
    return document.readyState; // 'loading' / 'interactive' / 'complete'
  } catch(e) {
    return 'detached';
  }
};

// 自动重试逻辑(在外部脚本中)
/*
  for attempt in 1 2 3; do
    node scripts/connect_cdp.js <targetId> '<code>' --timeout=5000 && break
    echo "Retry $attempt failed, sleeping 2s..."
    sleep 2
  done
*/

错误速查表

问题 现象 诊断 解决
CDP 端口不通 curl :9222/json/version 无响应 lsof -i :9222 重启 Chrome 带 --remote-debugging-port 参数
WebSocket 拒绝 connect_cdp.js 超时 Chrome 缺少 --remote-allow-origins=* 添加该参数重启
找不到目标页面 页面列表为 [] 浏览器未打开任何页面 先用 open 命令打开目标 URL
eval 返回异常 CDP Error: -32603 JS 语法错误/选择器不存在 检查 JS 语法,用 document.querySelector() 确认元素存在
页面崩了 WS close 无 message 页面 JS 执行卡死 刷新页面或重新打开
脚本未安装 ws 模块 Error: Cannot find module 'ws' Node.js 缺依赖 npm install ws 或 cd 脚本目录 && npm init -y && npm install ws

高级操作

多任务并发

  1. 打开多个 Chrome Tab(通过 CDP Page.navigate)
  2. 每个子 Agent 连接不同的 tab ID
  3. 用户手动切换到对应 tab 查看效果
  4. 不抢焦点、不弹新窗口

打开新 Tab 并获取 ID:

NEW_TAB=$(curl -s -X PUT http://127.0.0.1:9222/json/new?http://目标URL)
NEW_ID=$(echo "$NEW_TAB" | python3 -c "import json,sys; print(json.load(sys.stdin)['id'])")
echo "New Tab ID: $NEW_ID"

监听控制台日志

// 启用 Console 域
// 发送 CDP 命令: {"id":1,"method":"Console.enable"}
// 然后 Console.messageAdded 事件会推送控制台日志

监听网络请求

// 启用 Network 域
// 发送 CDP 命令: {"id":1,"method":"Network.enable"}
// 然后 Network.requestWillBeSent 等事件会推送网络详情

测试用例(test-prompts)

场景 Prompt 预期结果
基础连接 修改当前页面的标题为 "CDP测试" 页面标题立即更新
颜色调整 把页面主背景色改为深蓝色 #1a1a2e 背景色立即变化
字体注入 从 Google Fonts 引入 Inter 字体并应用到 body 页面字体更新
液态效果 给页面添加液态渐变动画效果 页面出现渐变动态背景
隐藏元素 隐藏页面侧边栏 侧边栏消失
撤销修改 撤销所有 CDP 注入的修改 页面恢复原始状态
获取快照 保存当前页面的 DOM 快照 快照保存在 __cdp_snapshot
并发 Tab 在第二个 Tab 中修改标题 另一个 Tab 标题变化
截图验证 截取当前页面截图 截图保存在 /tmp/cdp_screenshot.png
状态修改 设置 localStorage 的 theme 为 dark 页面主题变化(如适用)

目录结构

cdp-live-edit-skill/
├── SKILL.md                    ← 本文件(入口 + 完整说明)
├── scripts/
│   ├── connect_cdp.js          ← 通用 CDP eval 连接脚本
│   ├── liquid_effect.js        ← 液态渐变动画注入
│   └── check_chrome_cdp.sh     ← 一键诊断脚本
├── references/                 ← 参考文档(可选)
│   └── chrome_cdp_cheatsheet.md
├── test-prompts/               ← 测试用例
└── darwin_score_v*.json        ← 达尔文评分记录

版本历史

版本 日期 变更
v2.0.0 2026-06-27 达尔文优化:新增配套脚本、多层错误处理、撤销机制、快捷命令、液态效果完整示例
v1.0.0 — 初始版本:基本 CDP 连接与注入流程

参考

Current listing version

1.0.0

Verify the source revision ↗

Quality assessment

Out of 100 · Assessment report from SkillPi LAB.

Scenario Value85/100

Highlights

  • 解决前端开发者实时调试网页的高频痛点
  • 提供完整的 CDP 实时注入工作流,无需修改源文件
  • 支持 CSS/JS/DOM 多种修改类型,实用性强
Trigger Precision88/100

Highlights

  • 触发词覆盖全面:实时编辑、在线修改、CDP编辑等
  • 边界清晰,不易与其他技能混淆
Structure and Standards82/100

Areas to improve

  • 文档长度略超建议 Reported severity: Minor

    SKILL.md 约 600 行,超过 500 行建议值

    Recommendation: 可考虑将部分高级操作或示例移至独立文档

  • description 重复 Reported severity: Minor

    frontmatter 和 skill_body 开头均有 description

    Recommendation: 保留一处即可,避免冗余

Highlights

  • 结构完整:前置条件→快速开始→核心工作流→常见操作→错误处理
  • 提供端到端示例和测试用例
  • frontmatter 信息完整(含版本和变更日志)
Execution Reliability90/100

Highlights

  • 多层错误处理:前置检查、运行时超时、异常恢复机制
  • 提供撤销机制,降低误操作风险
  • 支持多种调用方式(Node.js 脚本 + curl 轻量方案)
  • 配套诊断脚本 check_chrome_cdp.sh 提升可用性
Evidence Verifiability (mean of the first four)86/100

The arithmetic mean of the first four original scores, rounded to a whole number.

Static text checks

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

No current rules matched the text.

This score reflects rule matches in the text and is provided for reference before use. It excludes attachments and runtime behavior.

Permissions and checks before use

Automatically summarized from this main document. Matches may be examples or defensive advice; they are not actual permission declarations. Attachments, external dependencies and runtime behavior are not covered.

  • Save or modify files

    Confirm the output directory and whether existing files will be replaced. Back up important files and prefer a new output directory.

    Mentioned in main document · lines 368
  • Install or fetch external dependencies

    Use official sources and pin versions. Check install scripts in an isolated environment. This document check does not cover code downloaded later.

    Mentioned in main document · lines 104, 428
  • Invoke commands or scripts

    Read the script and arguments first. Use ordinary privileges and a scoped directory; confirm installation or execution in your host tool.

    Mentioned in main document · lines 68
Domains or addresses referenced in the document

These addresses may be documentation links or examples, not an approved network allowlist. Verify actual destinations and outgoing data before use.

  • 127.0.0.1
  • chromedevtools.github.io
  • fonts.googleapis.com

These notices grant no permissions. Your host tool must still confirm file changes, secrets, external transfers or costs as needed.

Security rating and access scope

safe · Static evidence review; not a runtime safety guarantee.

Before use, confirm and authorize actual file access, external services and network destinations in your host. This review grants no runtime permissions.