目录
解锁生产力:用一段 JS 脚本让 ChatGPT 自动帮你写完一整本书

解锁生产力:用一段 JS 脚本让 ChatGPT 自动帮你写完一整本书
在利用 ChatGPT 撰写长篇内容(如书籍、教程、长篇连载)时,我们经常面临两个痛点:
-
上下文遗忘:如果在一个对话框里一直写,越往后模型越容易忘记前面的设定,输出质量逐渐下降。最好的做法是“分章节独立生成”或“定期重申 Prompt”。
-
重复劳动:每生成完一章,都需要人工复制下一章的 Prompt,粘贴、发送、等待。这个过程枯燥且耗时。
为什么不能写个脚本,让它自动帮我点“发送”,写完一章自动写下一章呢?
本文将分享一段浏览器控制台(Console)脚本,它能在 ChatGPT 网页版上挂载一个悬浮控制面板,全自动执行“填入 Prompt -> 点击发送 -> 等待生成 -> 发送下一条”的循环。
核心原理
ChatGPT 的网页版(以及大多数现代 SPA 应用)使用 React 构建。简单的 element.value = "text" 并不能触发 React 的状态更新,这会导致你明明填入了文字,点击发送按钮时却提示“内容为空”。
要实现自动化,我们需要攻克三个技术点:
-
模拟 React 输入:需要通过
dispatchEvent触发input事件,并利用_valueTrackerHack 来确保 React 感知到数据变化。 -
元素定位适配:ChatGPT 的 UI 经常更新,输入框可能是
textarea也可能是contenteditable div,发送按钮可能是图标也可能是文字。脚本需要具备一定的容错性。 -
状态检测:如何判断 AI 已经写完了?通过轮询检测“停止生成”按钮是否存在,或者发送按钮是否恢复可用状态。
脚本代码实现
以下是通用版脚本。你可以将它保存为书签,或者直接在控制台中运行。
注意:脚本仅在当前页面有效,刷新页面后需要重新运行。
// ============================================================================
// 🤖 ChatGPT 自动内容生成器 - 通用版
// ============================================================================
(function() {
// ----------------------------------------------------------------
// 1. 配置区域:在这里定义你的 System Prompt 和章节列表
// ----------------------------------------------------------------
const SYSTEM_PROMPT = `你是一位专业的技术书籍作者。
任务:撰写关于《深入理解现代Web架构》的书籍。
要求:
1. 风格通俗易懂,配合代码示例。
2. 使用标准 Markdown 格式。
3. 不要使用“好的”等客套话,直接输出正文。`;
// 每一项代表一次对话交互
const taskQueue = [
{
title: "第1章:Web架构演变史",
content: SYSTEM_PROMPT + "\n\n请撰写第1章:从单体应用到微服务。请详细介绍..."
},
{
title: "第2章:前端渲染模式",
content: "请继续撰写第2章:CSR, SSR, SSG 与 ISR 的区别与选型策略..."
},
{
title: "第3章:边缘计算与Serverless",
content: "请继续撰写第3章:边缘计算在现代前端部署中的应用..."
},
// 你可以在这里添加更多章节...
];
// ----------------------------------------------------------------
// 2. UI 构建:创建悬浮控制面板
// ----------------------------------------------------------------
const panel = document.createElement('div');
panel.style.cssText = 'position:fixed; top:20px; right:20px; width:300px; background:white; border:1px solid #e5e5e5; box-shadow:0 10px 15px -3px rgba(0,0,0,0.1); z-index:9999; padding:16px; border-radius:12px; font-family:-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;';
panel.innerHTML = `
<div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:12px;">
<h3 style="margin:0; font-weight:600; font-size:16px; color:#1a1a1a;">🤖 自动写作助手</h3>
<span style="font-size:10px; background:#f3f4f6; padding:2px 6px; border-radius:4px; color:#6b7280;">v1.0</span>
</div>
<div id="status-box" style="margin-bottom:12px; padding:8px 12px; background:#f9fafb; border-radius:6px; font-size:13px; color:#4b5563; border:1px solid #e5e7eb;">准备就绪</div>
<div id="progress-list" style="max-height:240px; overflow-y:auto; margin-bottom:12px; border:1px solid #e5e7eb; border-radius:6px;"></div>
<button id="start-btn" style="width:100%; background:#10a37f; color:white; border:none; padding:10px; border-radius:6px; cursor:pointer; font-weight:600; font-size:14px; transition:background 0.2s;">开始自动运行</button>
<button id="stop-btn" style="width:100%; background:#ef4444; color:white; border:none; padding:10px; border-radius:6px; cursor:pointer; font-weight:600; font-size:14px; display:none;">停止运行</button>
`;
document.body.appendChild(panel);
const listEl = panel.querySelector('#progress-list');
taskQueue.forEach((task, i) => {
const item = document.createElement('div');
item.id = `task-${i}`;
item.style.padding = '8px 12px';
item.style.borderBottom = '1px solid #f3f4f6';
item.style.fontSize = '13px';
item.style.color = '#374151';
item.innerText = `${i + 1}. ${task.title}`;
listEl.appendChild(item);
});
// ----------------------------------------------------------------
// 3. 核心逻辑:模拟输入与状态机
// ----------------------------------------------------------------
let currentIndex = 0;
let isRunning = false;
let checkTimer = null;
// 核心黑魔法:模拟 React 输入
function setNativeValue(element, value) {
// 适配 contenteditable (新版 ChatGPT UI)
if (element.contentEditable === 'true') {
element.innerHTML = '';
const p = document.createElement('p');
p.innerText = value;
element.appendChild(p);
element.dispatchEvent(new Event('input', { bubbles: true }));
element.focus();
return;
}
// 适配 Textarea (旧版 ChatGPT UI)
const lastValue = element.value;
element.value = value;
const event = new Event('input', { bubbles: true });
const tracker = element._valueTracker;
if (tracker) tracker.setValue(lastValue);
element.dispatchEvent(event);
}
// 智能获取输入框
function getTextArea() {
return document.querySelector('#prompt-textarea') ||
document.querySelector('div[contenteditable="true"]') ||
document.querySelector('textarea');
}
// 智能获取发送按钮 (适配不同样式的发送键)
function getSendButton() {
// 策略1: data-testid 属性
let btn = document.querySelector('[data-testid="send-button"]');
if (btn && !btn.disabled) return btn;
// 策略2: aria-label
btn = document.querySelector('button[aria-label="Send prompt"]');
if (btn && !btn.disabled) return btn;
// 策略3: 寻找输入框容器内最右下角的按钮 (通常是黑色的发送/语音钮)
const footer = document.querySelector('form') || document.querySelector('.relative.flex.h-full.max-w-full');
if (footer) {
const allButtons = footer.querySelectorAll('button');
const lastBtn = allButtons[allButtons.length - 1];
if (lastBtn) return lastBtn;
}
return null;
}
// 判断 AI 是否正在生成
function isGenerating() {
// 如果能找到“停止生成”按钮,说明正在忙
const stopBtn = document.querySelector('[aria-label="Stop generating"]') ||
document.querySelector('[data-testid="stop-button"]');
if (stopBtn) return true;
// 如果发送按钮被禁用,也说明可能正在忙
const sendBtn = getSendButton();
if (sendBtn && sendBtn.disabled) return true;
return false;
}
async function executeNextTask() {
if (!isRunning || currentIndex >= taskQueue.length) {
updateStatus(currentIndex >= taskQueue.length ? "✅ 全部任务完成!" : "已停止");
toggleButtons(false);
return;
}
const task = taskQueue[currentIndex];
updateStatus(`📝 正在输入: ${task.title}...`);
highlightCurrent(currentIndex);
const textarea = getTextArea();
if (!textarea) return alert("❌ 错误:找不到输入框");
// 1. 填入内容
textarea.focus();
setNativeValue(textarea, task.content);
// 2. 等待 UI 响应 (让发送按钮从灰色/语音图标变为可用状态)
await new Promise(r => setTimeout(r, 1500));
// 3. 点击发送
const sendBtn = getSendButton();
if (sendBtn) {
sendBtn.click();
updateStatus(`🚀 已发送,等待生成中...`);
await new Promise(r => setTimeout(r, 2000)); // 给它一点反应时间
monitorProgress(); // 进入监控模式
} else {
// 如果找不到按钮,尝试回车大法
updateStatus("⚠️ 未找到按钮,尝试回车发送...");
textarea.dispatchEvent(new KeyboardEvent('keydown', {
key: 'Enter', code: 'Enter', keyCode: 13, bubbles: true, cancelable: true
}));
monitorProgress();
}
}
function monitorProgress() {
checkTimer = setInterval(() => {
if (!isRunning) { clearInterval(checkTimer); return; }
if (!isGenerating()) {
// 生成结束
clearInterval(checkTimer);
markCompleted(currentIndex);
currentIndex++;
// 冷却时间,模拟人类思考,避免被判定为机器人
updateStatus("☕ 本章完成,休息 5 秒...");
setTimeout(executeNextTask, 5000);
}
}, 3000); // 每3秒轮询一次状态
}
// 辅助函数
function updateStatus(text) { panel.querySelector('#status-box').innerText = text; }
function toggleButtons(running) {
panel.querySelector('#start-btn').style.display = running ? 'none' : 'block';
panel.querySelector('#stop-btn').style.display = running ? 'block' : 'none';
}
function highlightCurrent(idx) {
const el = panel.querySelector(`#task-${idx}`);
if(el) el.style.background = '#eff6ff';
}
function markCompleted(idx) {
const el = panel.querySelector(`#task-${idx}`);
if(el) { el.style.background = 'transparent'; el.style.opacity = '0.5'; el.style.textDecoration = 'line-through'; }
}
// 启动监听
panel.querySelector('#start-btn').onclick = () => { isRunning = true; toggleButtons(true); executeNextTask(); };
panel.querySelector('#stop-btn').onclick = () => { isRunning = false; clearInterval(checkTimer); updateStatus("已手动停止"); toggleButtons(false); };
})();
如何使用
这是一段 "粘贴即用" 的代码,不需要安装任何浏览器插件。
-
准备内容:
-
将代码复制到你的文本编辑器中。
-
修改最上方的
taskQueue数组,将title和content替换成你想要生成的书籍章节或长文大纲。 -
Tip: 建议在
content中包含 System Prompt,以确保每一章的风格一致(例如:“作为一名资深工程师,请撰写...”)。
-
-
注入脚本:
-
打开 ChatGPT 官网。
-
按下
F12键(或右键 -> 检查)打开开发者工具。 -
切换到 Console(控制台) 标签页。
-
粘贴修改好的代码,按下 Enter 键。
-
-
开始自动化:
-
你会看到网页右上角出现了一个白色的悬浮面板。
-
点击绿色的 "开始自动运行" 按钮。
-
脚本会自动将第一章内容填入对话框并发送。
-
此刻你可以去喝杯咖啡,脚本会轮询检测生成状态,一旦当前章节生成完毕,它会自动休息 5 秒,然后发送下一章。
-
避坑指南
-
不要刷新页面:这是一个临时注入的脚本,刷新页面后脚本会消失。如果需要长时间使用,可以考虑使用 Tampermonkey(油猴)插件将其保存为固定脚本。
-
保持前台运行:虽然现代浏览器支持后台运行 JS,但为了避免浏览器的资源休眠策略导致轮询暂停,建议将 ChatGPT 页面保持在单独的窗口中展示。
-
API 限流:如果你设置的章节过多,可能会触发 ChatGPT 的每小时消息限制(GPT-4 用户尤甚)。建议将
setTimeout的休息时间适当调长(比如 10-20 秒)。 -
元素定位失败:ChatGPT 的前端代码更新非常频繁。如果某天脚本突然不工作了(比如填不进去字,或者找不到发送按钮),通常是因为 CSS 类名或 DOM 结构变了。这时你需要检查
getTextArea和getSendButton中的选择器是否依然有效。
总结
通过这个脚本,我们将“人机交互”转变为“简单的自动化流程
2762



被折叠的 条评论
为什么被折叠?



