Files
yu-zhi-ran/automation/fill_wechat_editor.js
T

82 lines
2.9 KiB
JavaScript

// 微信公众号编辑器自动填充脚本
// 用法: node fill_wechat_editor.js <markdown_file> <images_dir>
// 连接: chrome://inspect 或通过 agent-browser 转发
const fs = require('fs');
const http = require('http');
const [, , markdownFile, imagesDir] = process.argv;
if (!markdownFile || !imagesDir) {
console.error('用法: node fill_wechat_editor.js <markdown_file> <images_dir>');
process.exit(1);
}
const title = fs.readFileSync(markdownFile, 'utf8').split('\n')[0].replace(/^#\s+/, '');
const body = fs.readFileSync(markdownFile, 'utf8')
.split('\n')
.slice(1)
.join('\n')
.replace(/\n\n+/g, '\n\n');
const coverImg = `${imagesDir}/05-封面图.png`;
// 微信公众号编辑器核心:获取 contenteditable 区域
const FILL_SCRIPT = `
(function() {
// 1. 查找标题输入框
const titleInput = document.querySelector('.rich_media_title input[type="text"], input[placeholder*="标题"], [data-role="title"]');
if (!titleInput) return { error: '未找到标题输入框' };
// 2. 查找正文编辑器(多个可能)
const editors = [
document.querySelector('.rich_media_content [contenteditable="true"]'),
document.querySelector('[data-role="editor"]'),
document.querySelector('.editor'),
document.querySelector('#js_content'),
document.querySelector('.weui-desktop-editor__editable')
].filter(el => el);
if (editors.length === 0) return { error: '未找到正文编辑器' };
// 3. 填充标题
titleInput.focus();
titleInput.value = '';
titleInput.dispatchEvent(new Event('input', { bubbles: true }));
// 4. 填充正文
const editor = editors[0];
editor.focus();
editor.innerHTML = '';
// 按段落分割,生成带换行的HTML
const paragraphs = \`${body}\`.split('\\n\\n').map(p => `<p>${p.replace(/\\n/g, '<br>')}</p>`).join('');
editor.innerHTML = paragraphs;
// 5. 上传封面图(如果有)
if (${fs.existsSync(coverImg)}) {
// 查找图片上传按钮
const imgBtn = document.querySelector('[data-role="image"], .weui-desktop-editor__tool-img, button[title*="图片"]');
if (imgBtn) {
imgBtn.click();
// 等待文件选择器
setTimeout(() => {
const fileInput = document.querySelector('input[type="file"]');
if (fileInput) {
// 创建 DataTransfer 模拟文件选择
const file = new File([''], '${coverImg.split('/').pop()}', { type: 'image/png' });
const dt = new DataTransfer();
dt.items.add(file);
fileInput.files = dt.files;
fileInput.dispatchEvent(new Event('change', { bubbles: true }));
}
}, 500);
}
}
return { success: true, title: \`${title}\` };
})();
`;
console.log('等待连接...');
console.log('请在 VNC 中打开编辑器后,运行:');
console.log(' agent-browser --cdp 9222 eval \'' + FILL_SCRIPT.replace(/\n/g, ' ') + '\'');