main.ts 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960
  1. // 使用 CommonJS 格式
  2. const { app, BrowserWindow, ipcMain, shell, session, Menu, Tray, nativeImage, webContents } = require('electron');
  3. const { join } = require('path');
  4. const fs = require('fs');
  5. const http = require('http');
  6. const https = require('https');
  7. let mainWindow: typeof BrowserWindow.prototype | null = null;
  8. let tray: typeof Tray.prototype | null = null;
  9. let isQuitting = false;
  10. const VITE_DEV_SERVER_URL = process.env.VITE_DEV_SERVER_URL;
  11. function setupCertificateBypass() {
  12. app.on('certificate-error', (event: Event, _webContents: typeof webContents.prototype, _url: string, _error: string, _certificate: unknown, callback: (isTrusted: boolean) => void) => {
  13. event.preventDefault();
  14. callback(true);
  15. });
  16. }
  17. function setupCorsBypassForApiRequests() {
  18. const ses = session.defaultSession;
  19. if (!ses) return;
  20. ses.webRequest.onHeadersReceived((details: { url: string; responseHeaders?: Record<string, string[] | string> }, callback: (response: { responseHeaders: Record<string, string[] | string> }) => void) => {
  21. const url = String(details.url || '');
  22. const isHttp = url.startsWith('http://') || url.startsWith('https://');
  23. const isApiLike = url.includes('/api/') || url.includes('/uploads/');
  24. if (!isHttp || !isApiLike) {
  25. callback({ responseHeaders: details.responseHeaders || {} });
  26. return;
  27. }
  28. const responseHeaders = { ...(details.responseHeaders || {}) };
  29. // 移除服务端已有的 CORS 头,避免与下面设置的值合并成 "origin1, *" 导致违规
  30. const corsKeys = ['access-control-allow-origin', 'Access-Control-Allow-Origin'];
  31. corsKeys.forEach((k) => delete responseHeaders[k]);
  32. responseHeaders['access-control-allow-origin'] = ['*'];
  33. responseHeaders['access-control-allow-methods'] = ['GET,POST,PUT,PATCH,DELETE,OPTIONS'];
  34. responseHeaders['access-control-allow-headers'] = ['Authorization,Content-Type,X-Requested-With'];
  35. responseHeaders['access-control-expose-headers'] = ['Content-Disposition,Content-Type'];
  36. callback({ responseHeaders });
  37. });
  38. }
  39. function normalizeBaseUrl(url: string): string {
  40. const raw = String(url || '').trim();
  41. if (!raw) return '';
  42. try {
  43. const u = new URL(raw);
  44. return `${u.protocol}//${u.host}`.replace(/\/$/, '');
  45. } catch {
  46. return raw.replace(/\/$/, '');
  47. }
  48. }
  49. function requestJson(url: string, timeoutMs: number): Promise<{ ok: boolean; status?: number; data?: any; error?: string }> {
  50. return new Promise((resolve) => {
  51. const u = new URL(url);
  52. const isHttps = u.protocol === 'https:';
  53. const lib = isHttps ? https : http;
  54. // Windows 上 localhost 常被解析为 ::1,而后端仅监听 127.0.0.1,导致 ECONNREFUSED
  55. const hostname = (u.hostname === 'localhost' || u.hostname === '::1') ? '127.0.0.1' : u.hostname;
  56. const req = lib.request({
  57. method: 'GET',
  58. protocol: u.protocol,
  59. hostname,
  60. port: u.port || (isHttps ? 443 : 80),
  61. path: `${u.pathname}${u.search}`,
  62. headers: {
  63. Accept: 'application/json',
  64. },
  65. timeout: timeoutMs,
  66. rejectUnauthorized: false,
  67. }, (res: any) => {
  68. const chunks: Buffer[] = [];
  69. res.on('data', (c: Buffer) => chunks.push(c));
  70. res.on('end', () => {
  71. const status = Number(res.statusCode || 0);
  72. const rawText = Buffer.concat(chunks).toString('utf-8');
  73. if (status < 200 || status >= 300) {
  74. resolve({ ok: false, status, error: `HTTP ${status}` });
  75. return;
  76. }
  77. try {
  78. const json = rawText ? JSON.parse(rawText) : null;
  79. resolve({ ok: true, status, data: json });
  80. } catch {
  81. resolve({ ok: false, status, error: '响应不是 JSON' });
  82. }
  83. });
  84. });
  85. req.on('timeout', () => {
  86. req.destroy(new Error('timeout'));
  87. });
  88. req.on('error', (err: any) => {
  89. resolve({ ok: false, error: err?.message || '网络错误' });
  90. });
  91. req.end();
  92. });
  93. }
  94. // 获取图标路径
  95. function getIconPath() {
  96. return VITE_DEV_SERVER_URL
  97. ? join(__dirname, '../public/icons/icon-256.png')
  98. : join(__dirname, '../dist/icons/icon-256.png');
  99. }
  100. // 获取托盘图标路径
  101. function getTrayIconPath() {
  102. return VITE_DEV_SERVER_URL
  103. ? join(__dirname, '../public/icons/tray-icon.png')
  104. : join(__dirname, '../dist/icons/tray-icon.png');
  105. }
  106. // 创建托盘图标
  107. function createTrayIcon(): typeof nativeImage.prototype {
  108. const trayIconPath = getTrayIconPath();
  109. return nativeImage.createFromPath(trayIconPath);
  110. }
  111. // 创建系统托盘
  112. function createTray() {
  113. const trayIcon = createTrayIcon();
  114. tray = new Tray(trayIcon);
  115. const contextMenu = Menu.buildFromTemplate([
  116. {
  117. label: '显示主窗口',
  118. click: () => {
  119. if (mainWindow) {
  120. mainWindow.show();
  121. mainWindow.focus();
  122. }
  123. }
  124. },
  125. {
  126. label: '最小化到托盘',
  127. click: () => {
  128. mainWindow?.hide();
  129. }
  130. },
  131. { type: 'separator' },
  132. {
  133. label: '退出',
  134. click: () => {
  135. isQuitting = true;
  136. app.quit();
  137. }
  138. }
  139. ]);
  140. tray.setToolTip('智媒通');
  141. tray.setContextMenu(contextMenu);
  142. // 点击托盘图标显示窗口
  143. tray.on('click', () => {
  144. if (mainWindow) {
  145. if (mainWindow.isVisible()) {
  146. mainWindow.focus();
  147. } else {
  148. mainWindow.show();
  149. mainWindow.focus();
  150. }
  151. }
  152. });
  153. // 双击托盘图标显示窗口
  154. tray.on('double-click', () => {
  155. if (mainWindow) {
  156. mainWindow.show();
  157. mainWindow.focus();
  158. }
  159. });
  160. }
  161. function createWindow() {
  162. // 隐藏默认菜单栏
  163. Menu.setApplicationMenu(null);
  164. const iconPath = getIconPath();
  165. mainWindow = new BrowserWindow({
  166. width: 1400,
  167. height: 900,
  168. minWidth: 1200,
  169. minHeight: 700,
  170. icon: iconPath,
  171. webPreferences: {
  172. preload: join(__dirname, 'preload.js'),
  173. nodeIntegration: false,
  174. contextIsolation: true,
  175. webviewTag: true, // 启用 webview 标签
  176. },
  177. frame: false, // 无边框窗口,自定义标题栏
  178. transparent: false,
  179. backgroundColor: '#f0f2f5',
  180. show: false,
  181. });
  182. // 窗口准备好后再显示,避免白屏
  183. mainWindow.once('ready-to-show', () => {
  184. mainWindow?.show();
  185. setupWindowEvents();
  186. });
  187. // 加载页面
  188. if (VITE_DEV_SERVER_URL) {
  189. mainWindow.loadURL(VITE_DEV_SERVER_URL);
  190. mainWindow.webContents.openDevTools();
  191. } else {
  192. mainWindow.loadFile(join(__dirname, '../dist/index.html'));
  193. }
  194. // 处理外部链接
  195. mainWindow.webContents.setWindowOpenHandler(({ url }: { url: string }) => {
  196. shell.openExternal(url);
  197. return { action: 'deny' };
  198. });
  199. // 关闭按钮默认最小化到托盘
  200. mainWindow.on('close', (event: Event) => {
  201. if (!isQuitting) {
  202. event.preventDefault();
  203. mainWindow?.hide();
  204. // 显示托盘通知(仅首次)
  205. if (tray && !app.isPackaged) {
  206. // 开发模式下可以显示通知
  207. }
  208. }
  209. });
  210. mainWindow.on('closed', () => {
  211. mainWindow = null;
  212. });
  213. }
  214. // 单实例锁定
  215. const gotTheLock = app.requestSingleInstanceLock();
  216. if (!gotTheLock) {
  217. app.quit();
  218. } else {
  219. app.on('second-instance', () => {
  220. if (mainWindow) {
  221. mainWindow.show();
  222. if (mainWindow.isMinimized()) mainWindow.restore();
  223. mainWindow.focus();
  224. }
  225. });
  226. app.whenReady().then(() => {
  227. createTray();
  228. createWindow();
  229. // 配置 webview session,允许第三方 cookies 和跨域请求
  230. setupWebviewSessions();
  231. setupCertificateBypass();
  232. setupCorsBypassForApiRequests();
  233. app.on('activate', () => {
  234. if (BrowserWindow.getAllWindows().length === 0) {
  235. createWindow();
  236. } else if (mainWindow) {
  237. mainWindow.show();
  238. }
  239. });
  240. });
  241. }
  242. // 配置 webview sessions
  243. function setupWebviewSessions() {
  244. // 监听新的 webContents 创建
  245. app.on('web-contents-created', (_event: unknown, contents: typeof webContents.prototype) => {
  246. // 为 webview 类型的 webContents 配置
  247. if (contents.getType() === 'webview') {
  248. // 设置 User-Agent(模拟 Chrome 浏览器)
  249. contents.setUserAgent(
  250. 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
  251. );
  252. // 拦截自定义协议链接(如 bitbrowser://)的导航
  253. contents.on('will-navigate', (event: Event, url: string) => {
  254. if (!isAllowedUrl(url)) {
  255. console.log('[WebView] 阻止导航到自定义协议:', url);
  256. event.preventDefault();
  257. }
  258. });
  259. // 拦截新窗口打开(包括自定义协议)
  260. contents.setWindowOpenHandler(({ url }: { url: string }) => {
  261. if (!isAllowedUrl(url)) {
  262. console.log('[WebView] 阻止打开自定义协议窗口:', url);
  263. return { action: 'deny' };
  264. }
  265. // 对于正常的 http/https 链接,在当前 webview 中打开
  266. console.log('[WebView] 拦截新窗口,在当前页面打开:', url);
  267. contents.loadURL(url);
  268. return { action: 'deny' };
  269. });
  270. // 允许所有的权限请求(如摄像头、地理位置等)
  271. contents.session.setPermissionRequestHandler((_webContents: unknown, permission: string, callback: (granted: boolean) => void) => {
  272. // 允许所有权限请求
  273. callback(true);
  274. });
  275. // 配置 webRequest 修改请求头,移除可能暴露 Electron 的特征
  276. contents.session.webRequest.onBeforeSendHeaders((details: { requestHeaders: Record<string, string> }, callback: (response: { requestHeaders: Record<string, string> }) => void) => {
  277. // 移除可能暴露 Electron 的请求头
  278. delete details.requestHeaders['X-DevTools-Emulate-Network-Conditions-Client-Id'];
  279. // 确保有正常的 Origin 和 Referer
  280. if (!details.requestHeaders['Origin'] && !details.requestHeaders['origin']) {
  281. // 不添加 Origin,让浏览器自动处理
  282. }
  283. callback({ requestHeaders: details.requestHeaders });
  284. });
  285. }
  286. });
  287. }
  288. // 检查 URL 是否是允许的协议
  289. function isAllowedUrl(url: string): boolean {
  290. if (!url) return false;
  291. const lowerUrl = url.toLowerCase();
  292. return lowerUrl.startsWith('http://') ||
  293. lowerUrl.startsWith('https://') ||
  294. lowerUrl.startsWith('about:') ||
  295. lowerUrl.startsWith('data:');
  296. }
  297. // 阻止默认的 window-all-closed 行为,保持托盘运行
  298. app.on('window-all-closed', () => {
  299. // 不退出应用,保持托盘运行
  300. // 只有在 isQuitting 为 true 时才真正退出
  301. });
  302. // 应用退出前清理托盘
  303. app.on('before-quit', () => {
  304. isQuitting = true;
  305. });
  306. app.on('quit', () => {
  307. if (tray) {
  308. tray.destroy();
  309. tray = null;
  310. }
  311. });
  312. ipcMain.handle('test-server-connection', async (_event: unknown, args: { url: string }) => {
  313. try {
  314. const baseUrl = normalizeBaseUrl(args?.url);
  315. if (!baseUrl) return { ok: false, error: '未填写服务器地址' };
  316. const result = await requestJson(`${baseUrl}/api/health`, 5000);
  317. if (!result.ok) return { ok: false, error: result.error || '连接失败' };
  318. if (result.data?.status === 'ok') return { ok: true };
  319. return { ok: false, error: '服务器响应异常' };
  320. } catch (e: any) {
  321. return { ok: false, error: e?.message || '连接失败' };
  322. }
  323. });
  324. // Python 服务测试连接(主进程发起,支持 HTTP/HTTPS,无跨域限制)
  325. ipcMain.handle('test-python-service-connection', async (_event: unknown, args: { url: string }) => {
  326. try {
  327. const baseUrl = normalizeBaseUrl(args?.url);
  328. if (!baseUrl) return { ok: false, error: '未填写 Python 服务地址' };
  329. const result = await requestJson(`${baseUrl}/health`, 5000);
  330. if (!result.ok) return { ok: false, error: result.error || '连接失败' };
  331. return { ok: true };
  332. } catch (e: any) {
  333. return { ok: false, error: e?.message || '连接失败' };
  334. }
  335. });
  336. // IPC 处理
  337. ipcMain.handle('get-app-version', () => {
  338. return app.getVersion();
  339. });
  340. ipcMain.handle('get-platform', () => {
  341. return process.platform;
  342. });
  343. // 窗口控制
  344. ipcMain.on('window-minimize', () => {
  345. mainWindow?.minimize();
  346. });
  347. ipcMain.on('window-maximize', () => {
  348. if (mainWindow?.isMaximized()) {
  349. mainWindow.unmaximize();
  350. } else {
  351. mainWindow?.maximize();
  352. }
  353. });
  354. // 关闭窗口(最小化到托盘)
  355. ipcMain.on('window-close', () => {
  356. mainWindow?.hide();
  357. });
  358. // 真正退出应用
  359. ipcMain.on('app-quit', () => {
  360. isQuitting = true;
  361. app.quit();
  362. });
  363. // 获取窗口最大化状态
  364. ipcMain.handle('window-is-maximized', () => {
  365. return mainWindow?.isMaximized() || false;
  366. });
  367. // 监听窗口最大化/还原事件,通知渲染进程
  368. function setupWindowEvents() {
  369. mainWindow?.on('maximize', () => {
  370. mainWindow?.webContents.send('window-maximized', true);
  371. });
  372. mainWindow?.on('unmaximize', () => {
  373. mainWindow?.webContents.send('window-maximized', false);
  374. });
  375. }
  376. // 弹窗打开平台后台(独立窗口,不嵌入;用于实验,可回归为嵌入)
  377. ipcMain.handle('open-backend-external', async (_event: unknown, payload: { url: string; cookieData?: string; title?: string }) => {
  378. const { url, cookieData, title } = payload || {};
  379. if (!url || typeof url !== 'string') return;
  380. const partition = 'persist:backend-popup-' + Date.now();
  381. const ses = session.fromPartition(partition);
  382. if (cookieData && typeof cookieData === 'string' && cookieData.trim()) {
  383. const raw = cookieData.trim();
  384. let cookiesToSet: Array<{ name: string; value: string; domain?: string; path?: string }> = [];
  385. try {
  386. if (raw.startsWith('[') || raw.startsWith('{')) {
  387. const parsed = JSON.parse(raw);
  388. const arr = Array.isArray(parsed) ? parsed : (parsed?.cookies || []);
  389. cookiesToSet = arr.map((c: { name?: string; value?: string; domain?: string; path?: string }) => ({
  390. name: String(c?.name ?? '').trim(),
  391. value: String(c?.value ?? '').trim(),
  392. domain: c?.domain ? String(c.domain) : undefined,
  393. path: c?.path ? String(c.path) : '/',
  394. })).filter((c: { name: string }) => c.name);
  395. } else {
  396. raw.split(';').forEach((p: string) => {
  397. const idx = p.indexOf('=');
  398. if (idx > 0) {
  399. const name = p.slice(0, idx).trim();
  400. const value = p.slice(idx + 1).trim();
  401. if (name) cookiesToSet.push({ name, value, path: '/' });
  402. }
  403. });
  404. }
  405. } catch (e) {
  406. console.warn('[open-backend-external] 解析 cookie 失败', e);
  407. }
  408. const origin = new URL(url).origin;
  409. const hostname = new URL(url).hostname;
  410. const defaultDomain = hostname.startsWith('www.') ? hostname.slice(4) : hostname;
  411. const domainWithDot = defaultDomain.includes('.') ? '.' + defaultDomain.split('.').slice(-2).join('.') : undefined;
  412. for (const c of cookiesToSet) {
  413. try {
  414. await ses.cookies.set({
  415. url: origin + '/',
  416. name: c.name,
  417. value: c.value,
  418. domain: c.domain || domainWithDot || hostname,
  419. path: c.path || '/',
  420. });
  421. } catch (err) {
  422. console.warn('[open-backend-external] 设置 cookie 失败', c.name, err);
  423. }
  424. }
  425. }
  426. const win = new BrowserWindow({
  427. width: 1280,
  428. height: 800,
  429. title: title || '平台后台',
  430. icon: getIconPath(),
  431. webPreferences: {
  432. session: ses,
  433. nodeIntegration: false,
  434. contextIsolation: true,
  435. },
  436. show: false,
  437. });
  438. win.once('ready-to-show', () => {
  439. win.show();
  440. });
  441. await win.loadURL(url);
  442. return { ok: true };
  443. });
  444. // 获取 webview 的 cookies
  445. ipcMain.handle('get-webview-cookies', async (_event: unknown, partition: string, url: string) => {
  446. try {
  447. const ses = session.fromPartition(partition);
  448. const cookies = await ses.cookies.get({ url });
  449. return cookies;
  450. } catch (error) {
  451. console.error('获取 cookies 失败:', error);
  452. return [];
  453. }
  454. });
  455. // 获取 webview 的全部 cookies(按 partition)
  456. ipcMain.handle('get-webview-all-cookies', async (_event: unknown, partition: string) => {
  457. try {
  458. const ses = session.fromPartition(partition);
  459. return await ses.cookies.get({});
  460. } catch (error) {
  461. console.error('获取全部 cookies 失败:', error);
  462. return [];
  463. }
  464. });
  465. // 清除 webview 的 cookies
  466. ipcMain.handle('clear-webview-cookies', async (_event: unknown, partition: string) => {
  467. try {
  468. const ses = session.fromPartition(partition);
  469. await ses.clearStorageData({ storages: ['cookies'] });
  470. return true;
  471. } catch (error) {
  472. console.error('清除 cookies 失败:', error);
  473. return false;
  474. }
  475. });
  476. // 设置 webview 的 cookies
  477. ipcMain.handle('set-webview-cookies', async (_event: unknown, partition: string, cookies: Electron.CookiesSetDetails[]) => {
  478. try {
  479. if (!Array.isArray(cookies) || cookies.length === 0) {
  480. console.warn(`[Main] set-webview-cookies: cookies 为空, partition=${partition}`);
  481. return false;
  482. }
  483. console.log(`[Main] 设置 webview cookies, partition=${partition}, count=${cookies.length}`);
  484. const ses = session.fromPartition(partition);
  485. // 逐个设置 cookie
  486. let successCount = 0;
  487. for (const cookie of cookies) {
  488. try {
  489. // 确保 Cookie 格式正确
  490. const cookieToSet: Electron.CookiesSetDetails = {
  491. url: cookie.url,
  492. name: cookie.name,
  493. value: cookie.value,
  494. domain: cookie.domain,
  495. path: cookie.path || '/',
  496. };
  497. // 可选字段
  498. if (typeof cookie.expirationDate === 'number' && Number.isFinite(cookie.expirationDate) && cookie.expirationDate > 0) {
  499. cookieToSet.expirationDate = cookie.expirationDate;
  500. }
  501. if (cookie.httpOnly !== undefined) {
  502. cookieToSet.httpOnly = cookie.httpOnly;
  503. }
  504. if (cookie.secure !== undefined) {
  505. cookieToSet.secure = cookie.secure;
  506. }
  507. if (cookie.sameSite) {
  508. cookieToSet.sameSite = cookie.sameSite as 'no_restriction' | 'lax' | 'strict';
  509. }
  510. await ses.cookies.set(cookieToSet);
  511. successCount++;
  512. // 记录关键 Cookie
  513. if (cookie.name === 'BDUSS' || cookie.name === 'STOKEN' || cookie.name === 'sessionid') {
  514. console.log(`[Main] 成功设置关键 Cookie: ${cookie.name}, domain: ${cookie.domain}`);
  515. }
  516. } catch (error) {
  517. console.error(`[Main] 设置 cookie 失败 (${cookie.name}):`, error);
  518. }
  519. }
  520. console.log(`[Main] 成功设置 ${successCount}/${cookies.length} 个 cookies`);
  521. // 验证 Cookie 是否真的设置成功
  522. try {
  523. const setCookies = await ses.cookies.get({ domain: '.baidu.com' });
  524. console.log(`[Main] 验证:当前 session 中有 ${setCookies.length} 个百度 Cookie`);
  525. const keyNames = setCookies.slice(0, 5).map(c => c.name).join(', ');
  526. console.log(`[Main] 关键 Cookie 名称: ${keyNames}`);
  527. } catch (verifyError) {
  528. console.error('[Main] 验证 Cookie 失败:', verifyError);
  529. }
  530. return successCount > 0;
  531. } catch (error) {
  532. console.error('[Main] 设置 cookies 失败:', error);
  533. return false;
  534. }
  535. });
  536. // 截取 webview 页面截图(用于 AI 分析)
  537. ipcMain.handle('capture-webview-page', async (_event: unknown, webContentsId: number) => {
  538. try {
  539. const wc = webContents.fromId(webContentsId);
  540. if (!wc) {
  541. console.error('找不到 webContents:', webContentsId);
  542. return null;
  543. }
  544. const image = await wc.capturePage();
  545. if (!image || image.isEmpty()) {
  546. console.warn('截图为空');
  547. return null;
  548. }
  549. // 转换为 JPEG 格式的 Base64
  550. const buffer = image.toJPEG(80);
  551. return buffer.toString('base64');
  552. } catch (error) {
  553. console.error('截图失败:', error);
  554. return null;
  555. }
  556. });
  557. // 向 webview 发送鼠标点击事件
  558. ipcMain.handle('webview-send-mouse-click', async (_event: unknown, webContentsId: number, x: number, y: number) => {
  559. try {
  560. const wc = webContents.fromId(webContentsId);
  561. if (!wc) {
  562. console.error('找不到 webContents:', webContentsId);
  563. return false;
  564. }
  565. // 发送鼠标移动事件
  566. wc.sendInputEvent({
  567. type: 'mouseMove',
  568. x: Math.round(x),
  569. y: Math.round(y),
  570. });
  571. // 短暂延迟后发送点击事件
  572. await new Promise(resolve => setTimeout(resolve, 50));
  573. // 发送鼠标按下事件
  574. wc.sendInputEvent({
  575. type: 'mouseDown',
  576. x: Math.round(x),
  577. y: Math.round(y),
  578. button: 'left',
  579. clickCount: 1,
  580. });
  581. // 短暂延迟后发送鼠标抬起事件
  582. await new Promise(resolve => setTimeout(resolve, 50));
  583. wc.sendInputEvent({
  584. type: 'mouseUp',
  585. x: Math.round(x),
  586. y: Math.round(y),
  587. button: 'left',
  588. clickCount: 1,
  589. });
  590. console.log(`[webview-send-mouse-click] Clicked at (${x}, ${y})`);
  591. return true;
  592. } catch (error) {
  593. console.error('发送点击事件失败:', error);
  594. return false;
  595. }
  596. });
  597. // 向 webview 发送键盘输入事件
  598. ipcMain.handle('webview-send-text-input', async (_event: unknown, webContentsId: number, text: string) => {
  599. try {
  600. const wc = webContents.fromId(webContentsId);
  601. if (!wc) {
  602. console.error('找不到 webContents:', webContentsId);
  603. return false;
  604. }
  605. // 逐字符输入
  606. for (const char of text) {
  607. wc.sendInputEvent({
  608. type: 'char',
  609. keyCode: char,
  610. });
  611. await new Promise(resolve => setTimeout(resolve, 30));
  612. }
  613. console.log(`[webview-send-text-input] Typed: ${text}`);
  614. return true;
  615. } catch (error) {
  616. console.error('发送输入事件失败:', error);
  617. return false;
  618. }
  619. });
  620. // 获取 webview 页面元素位置
  621. ipcMain.handle('webview-get-element-position', async (_event: unknown, webContentsId: number, selector: string) => {
  622. try {
  623. const wc = webContents.fromId(webContentsId);
  624. if (!wc) {
  625. console.error('找不到 webContents:', webContentsId);
  626. return null;
  627. }
  628. const result = await wc.executeJavaScript(`
  629. (function() {
  630. const el = document.querySelector('${selector.replace(/'/g, "\\'")}');
  631. if (!el) return null;
  632. const rect = el.getBoundingClientRect();
  633. return {
  634. x: rect.left + rect.width / 2,
  635. y: rect.top + rect.height / 2,
  636. width: rect.width,
  637. height: rect.height
  638. };
  639. })()
  640. `);
  641. return result;
  642. } catch (error) {
  643. console.error('获取元素位置失败:', error);
  644. return null;
  645. }
  646. });
  647. // 通过文本内容查找并点击元素
  648. ipcMain.handle('webview-click-by-text', async (_event: unknown, webContentsId: number, text: string) => {
  649. try {
  650. const wc = webContents.fromId(webContentsId);
  651. if (!wc) {
  652. console.error('找不到 webContents:', webContentsId);
  653. return false;
  654. }
  655. // 查找包含指定文本的可点击元素的位置
  656. const position = await wc.executeJavaScript(`
  657. (function() {
  658. const searchText = '${text.replace(/'/g, "\\'")}';
  659. // 查找可点击元素
  660. const clickables = document.querySelectorAll('a, button, [role="button"], [onclick], input[type="submit"], input[type="button"]');
  661. for (const el of clickables) {
  662. if (el.textContent?.includes(searchText) || el.getAttribute('aria-label')?.includes(searchText) || el.getAttribute('title')?.includes(searchText)) {
  663. const rect = el.getBoundingClientRect();
  664. if (rect.width > 0 && rect.height > 0) {
  665. return { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 };
  666. }
  667. }
  668. }
  669. // 查找所有包含文本的元素
  670. const allElements = document.querySelectorAll('*');
  671. for (const el of allElements) {
  672. const text = el.innerText?.trim();
  673. if (text && text.length < 100 && text.includes(searchText)) {
  674. const rect = el.getBoundingClientRect();
  675. if (rect.width > 0 && rect.height > 0 && rect.width < 500) {
  676. return { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 };
  677. }
  678. }
  679. }
  680. return null;
  681. })()
  682. `);
  683. if (!position) {
  684. console.warn(`[webview-click-by-text] 未找到包含 "${text}" 的元素`);
  685. return false;
  686. }
  687. // 发送点击事件
  688. wc.sendInputEvent({ type: 'mouseMove', x: Math.round(position.x), y: Math.round(position.y) });
  689. await new Promise(resolve => setTimeout(resolve, 50));
  690. wc.sendInputEvent({ type: 'mouseDown', x: Math.round(position.x), y: Math.round(position.y), button: 'left', clickCount: 1 });
  691. await new Promise(resolve => setTimeout(resolve, 50));
  692. wc.sendInputEvent({ type: 'mouseUp', x: Math.round(position.x), y: Math.round(position.y), button: 'left', clickCount: 1 });
  693. console.log(`[webview-click-by-text] Clicked "${text}" at (${position.x}, ${position.y})`);
  694. return true;
  695. } catch (error) {
  696. console.error('通过文本点击失败:', error);
  697. return false;
  698. }
  699. });
  700. // ========== CDP 网络拦截功能 ==========
  701. // 存储每个 webContents 的网络拦截配置
  702. const networkInterceptors: Map<number, {
  703. patterns: Array<{ match: string, key: string }>;
  704. pendingRequests: Map<string, { url: string, timestamp: number }>;
  705. }> = new Map();
  706. // 启用 CDP 网络拦截
  707. ipcMain.handle('enable-network-intercept', async (_event: unknown, webContentsId: number, patterns: Array<{ match: string, key: string }>) => {
  708. try {
  709. const wc = webContents.fromId(webContentsId);
  710. if (!wc) {
  711. console.error('[CDP] 找不到 webContents:', webContentsId);
  712. return false;
  713. }
  714. // 如果已经有拦截器,先清理
  715. if (networkInterceptors.has(webContentsId)) {
  716. try {
  717. wc.debugger.detach();
  718. } catch (e) {
  719. // 忽略
  720. }
  721. }
  722. // 存储配置
  723. networkInterceptors.set(webContentsId, {
  724. patterns,
  725. pendingRequests: new Map()
  726. });
  727. // 附加调试器
  728. try {
  729. wc.debugger.attach('1.3');
  730. } catch (err: unknown) {
  731. const error = err as Error;
  732. if (!error.message?.includes('Already attached')) {
  733. throw err;
  734. }
  735. }
  736. // 启用网络监听
  737. await wc.debugger.sendCommand('Network.enable');
  738. // 监听网络响应
  739. wc.debugger.on('message', async (_e: unknown, method: string, params: {
  740. requestId?: string;
  741. response?: { url?: string; status?: number; mimeType?: string };
  742. encodedDataLength?: number;
  743. }) => {
  744. const config = networkInterceptors.get(webContentsId);
  745. if (!config) return;
  746. if (method === 'Network.responseReceived') {
  747. const { requestId, response } = params;
  748. if (!requestId || !response?.url) return;
  749. // 调试:打印百家号相关的所有 API 请求
  750. if (response.url.includes('baijiahao.baidu.com')) {
  751. if (response.url.includes('/pcui/') || response.url.includes('/article')) {
  752. console.log(`[CDP DEBUG] 百家号 API: ${response.url}`);
  753. }
  754. }
  755. // 检查是否匹配我们关注的 API
  756. for (const pattern of config.patterns) {
  757. if (response.url.includes(pattern.match)) {
  758. // 记录请求,等待响应完成
  759. config.pendingRequests.set(requestId, {
  760. url: response.url,
  761. timestamp: Date.now()
  762. });
  763. console.log(`[CDP] 匹配到 API: ${pattern.key} - ${response.url}`);
  764. break;
  765. }
  766. }
  767. }
  768. if (method === 'Network.loadingFinished') {
  769. const { requestId } = params;
  770. if (!requestId) return;
  771. const pending = config.pendingRequests.get(requestId);
  772. if (!pending) return;
  773. config.pendingRequests.delete(requestId);
  774. try {
  775. // 获取响应体
  776. const result = await wc.debugger.sendCommand('Network.getResponseBody', { requestId }) as { body: string; base64Encoded: boolean };
  777. let body = result.body;
  778. // 如果是 base64 编码,解码
  779. if (result.base64Encoded) {
  780. body = Buffer.from(body, 'base64').toString('utf8');
  781. }
  782. // 解析 JSON
  783. const data = JSON.parse(body);
  784. // 找到匹配的 key
  785. let matchedKey = '';
  786. for (const pattern of config.patterns) {
  787. if (pending.url.includes(pattern.match)) {
  788. matchedKey = pattern.key;
  789. break;
  790. }
  791. }
  792. if (matchedKey) {
  793. console.log(`[CDP] 获取到响应: ${matchedKey}`, JSON.stringify(data).substring(0, 200));
  794. // 发送到渲染进程
  795. mainWindow?.webContents.send('network-intercept-data', {
  796. webContentsId,
  797. key: matchedKey,
  798. url: pending.url,
  799. data
  800. });
  801. }
  802. } catch (err) {
  803. console.warn(`[CDP] 获取响应体失败:`, err);
  804. }
  805. }
  806. });
  807. console.log(`[CDP] 已启用网络拦截,webContentsId: ${webContentsId}, patterns:`, patterns.map(p => p.key));
  808. return true;
  809. } catch (error) {
  810. console.error('[CDP] 启用网络拦截失败:', error);
  811. return false;
  812. }
  813. });
  814. // 禁用 CDP 网络拦截
  815. ipcMain.handle('disable-network-intercept', async (_event: unknown, webContentsId: number) => {
  816. try {
  817. const wc = webContents.fromId(webContentsId);
  818. if (wc) {
  819. try {
  820. wc.debugger.detach();
  821. } catch (e) {
  822. // 忽略
  823. }
  824. }
  825. networkInterceptors.delete(webContentsId);
  826. console.log(`[CDP] 已禁用网络拦截,webContentsId: ${webContentsId}`);
  827. return true;
  828. } catch (error) {
  829. console.error('[CDP] 禁用网络拦截失败:', error);
  830. return false;
  831. }
  832. });
  833. // 更新网络拦截的 patterns
  834. ipcMain.handle('update-network-patterns', async (_event: unknown, webContentsId: number, patterns: Array<{ match: string, key: string }>) => {
  835. const config = networkInterceptors.get(webContentsId);
  836. if (config) {
  837. config.patterns = patterns;
  838. console.log(`[CDP] 已更新 patterns,webContentsId: ${webContentsId}`);
  839. return true;
  840. }
  841. return false;
  842. });