main.ts 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747
  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. let mainWindow: typeof BrowserWindow.prototype | null = null;
  6. let tray: typeof Tray.prototype | null = null;
  7. let isQuitting = false;
  8. const VITE_DEV_SERVER_URL = process.env.VITE_DEV_SERVER_URL;
  9. // 获取图标路径
  10. function getIconPath() {
  11. return VITE_DEV_SERVER_URL
  12. ? join(__dirname, '../public/icons/icon-256.png')
  13. : join(__dirname, '../dist/icons/icon-256.png');
  14. }
  15. // 获取托盘图标路径
  16. function getTrayIconPath() {
  17. return VITE_DEV_SERVER_URL
  18. ? join(__dirname, '../public/icons/tray-icon.png')
  19. : join(__dirname, '../dist/icons/tray-icon.png');
  20. }
  21. // 创建托盘图标
  22. function createTrayIcon(): typeof nativeImage.prototype {
  23. const trayIconPath = getTrayIconPath();
  24. return nativeImage.createFromPath(trayIconPath);
  25. }
  26. // 创建系统托盘
  27. function createTray() {
  28. const trayIcon = createTrayIcon();
  29. tray = new Tray(trayIcon);
  30. const contextMenu = Menu.buildFromTemplate([
  31. {
  32. label: '显示主窗口',
  33. click: () => {
  34. if (mainWindow) {
  35. mainWindow.show();
  36. mainWindow.focus();
  37. }
  38. }
  39. },
  40. {
  41. label: '最小化到托盘',
  42. click: () => {
  43. mainWindow?.hide();
  44. }
  45. },
  46. { type: 'separator' },
  47. {
  48. label: '退出',
  49. click: () => {
  50. isQuitting = true;
  51. app.quit();
  52. }
  53. }
  54. ]);
  55. tray.setToolTip('多平台媒体管理系统');
  56. tray.setContextMenu(contextMenu);
  57. // 点击托盘图标显示窗口
  58. tray.on('click', () => {
  59. if (mainWindow) {
  60. if (mainWindow.isVisible()) {
  61. mainWindow.focus();
  62. } else {
  63. mainWindow.show();
  64. mainWindow.focus();
  65. }
  66. }
  67. });
  68. // 双击托盘图标显示窗口
  69. tray.on('double-click', () => {
  70. if (mainWindow) {
  71. mainWindow.show();
  72. mainWindow.focus();
  73. }
  74. });
  75. }
  76. function createWindow() {
  77. // 隐藏默认菜单栏
  78. Menu.setApplicationMenu(null);
  79. const iconPath = getIconPath();
  80. mainWindow = new BrowserWindow({
  81. width: 1400,
  82. height: 900,
  83. minWidth: 1200,
  84. minHeight: 700,
  85. icon: iconPath,
  86. webPreferences: {
  87. preload: join(__dirname, 'preload.js'),
  88. nodeIntegration: false,
  89. contextIsolation: true,
  90. webviewTag: true, // 启用 webview 标签
  91. },
  92. frame: false, // 无边框窗口,自定义标题栏
  93. transparent: false,
  94. backgroundColor: '#f0f2f5',
  95. show: false,
  96. });
  97. // 窗口准备好后再显示,避免白屏
  98. mainWindow.once('ready-to-show', () => {
  99. mainWindow?.show();
  100. setupWindowEvents();
  101. });
  102. // 加载页面
  103. if (VITE_DEV_SERVER_URL) {
  104. mainWindow.loadURL(VITE_DEV_SERVER_URL);
  105. mainWindow.webContents.openDevTools();
  106. } else {
  107. mainWindow.loadFile(join(__dirname, '../dist/index.html'));
  108. }
  109. // 处理外部链接
  110. mainWindow.webContents.setWindowOpenHandler(({ url }: { url: string }) => {
  111. shell.openExternal(url);
  112. return { action: 'deny' };
  113. });
  114. // 关闭按钮默认最小化到托盘
  115. mainWindow.on('close', (event: Event) => {
  116. if (!isQuitting) {
  117. event.preventDefault();
  118. mainWindow?.hide();
  119. // 显示托盘通知(仅首次)
  120. if (tray && !app.isPackaged) {
  121. // 开发模式下可以显示通知
  122. }
  123. }
  124. });
  125. mainWindow.on('closed', () => {
  126. mainWindow = null;
  127. });
  128. }
  129. // 单实例锁定
  130. const gotTheLock = app.requestSingleInstanceLock();
  131. if (!gotTheLock) {
  132. app.quit();
  133. } else {
  134. app.on('second-instance', () => {
  135. if (mainWindow) {
  136. mainWindow.show();
  137. if (mainWindow.isMinimized()) mainWindow.restore();
  138. mainWindow.focus();
  139. }
  140. });
  141. app.whenReady().then(() => {
  142. createTray();
  143. createWindow();
  144. // 配置 webview session,允许第三方 cookies 和跨域请求
  145. setupWebviewSessions();
  146. app.on('activate', () => {
  147. if (BrowserWindow.getAllWindows().length === 0) {
  148. createWindow();
  149. } else if (mainWindow) {
  150. mainWindow.show();
  151. }
  152. });
  153. });
  154. }
  155. // 配置 webview sessions
  156. function setupWebviewSessions() {
  157. // 监听新的 webContents 创建
  158. app.on('web-contents-created', (_event: unknown, contents: typeof webContents.prototype) => {
  159. // 为 webview 类型的 webContents 配置
  160. if (contents.getType() === 'webview') {
  161. // 设置 User-Agent(模拟 Chrome 浏览器)
  162. contents.setUserAgent(
  163. 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
  164. );
  165. // 拦截自定义协议链接(如 bitbrowser://)的导航
  166. contents.on('will-navigate', (event: Event, url: string) => {
  167. if (!isAllowedUrl(url)) {
  168. console.log('[WebView] 阻止导航到自定义协议:', url);
  169. event.preventDefault();
  170. }
  171. });
  172. // 拦截新窗口打开(包括自定义协议)
  173. contents.setWindowOpenHandler(({ url }: { url: string }) => {
  174. if (!isAllowedUrl(url)) {
  175. console.log('[WebView] 阻止打开自定义协议窗口:', url);
  176. return { action: 'deny' };
  177. }
  178. // 对于正常的 http/https 链接,在当前 webview 中打开
  179. console.log('[WebView] 拦截新窗口,在当前页面打开:', url);
  180. contents.loadURL(url);
  181. return { action: 'deny' };
  182. });
  183. // 允许所有的权限请求(如摄像头、地理位置等)
  184. contents.session.setPermissionRequestHandler((_webContents: unknown, permission: string, callback: (granted: boolean) => void) => {
  185. // 允许所有权限请求
  186. callback(true);
  187. });
  188. // 配置 webRequest 修改请求头,移除可能暴露 Electron 的特征
  189. contents.session.webRequest.onBeforeSendHeaders((details: { requestHeaders: Record<string, string> }, callback: (response: { requestHeaders: Record<string, string> }) => void) => {
  190. // 移除可能暴露 Electron 的请求头
  191. delete details.requestHeaders['X-DevTools-Emulate-Network-Conditions-Client-Id'];
  192. // 确保有正常的 Origin 和 Referer
  193. if (!details.requestHeaders['Origin'] && !details.requestHeaders['origin']) {
  194. // 不添加 Origin,让浏览器自动处理
  195. }
  196. callback({ requestHeaders: details.requestHeaders });
  197. });
  198. }
  199. });
  200. }
  201. // 检查 URL 是否是允许的协议
  202. function isAllowedUrl(url: string): boolean {
  203. if (!url) return false;
  204. const lowerUrl = url.toLowerCase();
  205. return lowerUrl.startsWith('http://') ||
  206. lowerUrl.startsWith('https://') ||
  207. lowerUrl.startsWith('about:') ||
  208. lowerUrl.startsWith('data:');
  209. }
  210. // 阻止默认的 window-all-closed 行为,保持托盘运行
  211. app.on('window-all-closed', () => {
  212. // 不退出应用,保持托盘运行
  213. // 只有在 isQuitting 为 true 时才真正退出
  214. });
  215. // 应用退出前清理托盘
  216. app.on('before-quit', () => {
  217. isQuitting = true;
  218. });
  219. app.on('quit', () => {
  220. if (tray) {
  221. tray.destroy();
  222. tray = null;
  223. }
  224. });
  225. // IPC 处理
  226. ipcMain.handle('get-app-version', () => {
  227. return app.getVersion();
  228. });
  229. ipcMain.handle('get-platform', () => {
  230. return process.platform;
  231. });
  232. // 窗口控制
  233. ipcMain.on('window-minimize', () => {
  234. mainWindow?.minimize();
  235. });
  236. ipcMain.on('window-maximize', () => {
  237. if (mainWindow?.isMaximized()) {
  238. mainWindow.unmaximize();
  239. } else {
  240. mainWindow?.maximize();
  241. }
  242. });
  243. // 关闭窗口(最小化到托盘)
  244. ipcMain.on('window-close', () => {
  245. mainWindow?.hide();
  246. });
  247. // 真正退出应用
  248. ipcMain.on('app-quit', () => {
  249. isQuitting = true;
  250. app.quit();
  251. });
  252. // 获取窗口最大化状态
  253. ipcMain.handle('window-is-maximized', () => {
  254. return mainWindow?.isMaximized() || false;
  255. });
  256. // 监听窗口最大化/还原事件,通知渲染进程
  257. function setupWindowEvents() {
  258. mainWindow?.on('maximize', () => {
  259. mainWindow?.webContents.send('window-maximized', true);
  260. });
  261. mainWindow?.on('unmaximize', () => {
  262. mainWindow?.webContents.send('window-maximized', false);
  263. });
  264. }
  265. // 获取 webview 的 cookies
  266. ipcMain.handle('get-webview-cookies', async (_event: unknown, partition: string, url: string) => {
  267. try {
  268. const ses = session.fromPartition(partition);
  269. const cookies = await ses.cookies.get({ url });
  270. return cookies;
  271. } catch (error) {
  272. console.error('获取 cookies 失败:', error);
  273. return [];
  274. }
  275. });
  276. // 清除 webview 的 cookies
  277. ipcMain.handle('clear-webview-cookies', async (_event: unknown, partition: string) => {
  278. try {
  279. const ses = session.fromPartition(partition);
  280. await ses.clearStorageData({ storages: ['cookies'] });
  281. return true;
  282. } catch (error) {
  283. console.error('清除 cookies 失败:', error);
  284. return false;
  285. }
  286. });
  287. // 设置 webview 的 cookies
  288. ipcMain.handle('set-webview-cookies', async (_event: unknown, partition: string, cookies: Electron.CookiesSetDetails[]) => {
  289. try {
  290. console.log(`[Main] 设置 webview cookies, partition=${partition}, count=${cookies.length}`);
  291. const ses = session.fromPartition(partition);
  292. // 逐个设置 cookie
  293. let successCount = 0;
  294. for (const cookie of cookies) {
  295. try {
  296. // 确保 Cookie 格式正确
  297. const cookieToSet: Electron.CookiesSetDetails = {
  298. url: cookie.url,
  299. name: cookie.name,
  300. value: cookie.value,
  301. domain: cookie.domain,
  302. path: cookie.path || '/',
  303. };
  304. // 可选字段
  305. if (cookie.expirationDate) {
  306. cookieToSet.expirationDate = cookie.expirationDate;
  307. }
  308. if (cookie.httpOnly !== undefined) {
  309. cookieToSet.httpOnly = cookie.httpOnly;
  310. }
  311. if (cookie.secure !== undefined) {
  312. cookieToSet.secure = cookie.secure;
  313. }
  314. if (cookie.sameSite) {
  315. cookieToSet.sameSite = cookie.sameSite as 'no_restriction' | 'lax' | 'strict';
  316. }
  317. await ses.cookies.set(cookieToSet);
  318. successCount++;
  319. // 记录关键 Cookie
  320. if (cookie.name === 'BDUSS' || cookie.name === 'STOKEN' || cookie.name === 'sessionid') {
  321. console.log(`[Main] 成功设置关键 Cookie: ${cookie.name}, domain: ${cookie.domain}`);
  322. }
  323. } catch (error) {
  324. console.error(`[Main] 设置 cookie 失败 (${cookie.name}):`, error);
  325. }
  326. }
  327. console.log(`[Main] 成功设置 ${successCount}/${cookies.length} 个 cookies`);
  328. // 验证 Cookie 是否真的设置成功
  329. try {
  330. const setCookies = await ses.cookies.get({ domain: '.baidu.com' });
  331. console.log(`[Main] 验证:当前 session 中有 ${setCookies.length} 个百度 Cookie`);
  332. const keyNames = setCookies.slice(0, 5).map(c => c.name).join(', ');
  333. console.log(`[Main] 关键 Cookie 名称: ${keyNames}`);
  334. } catch (verifyError) {
  335. console.error('[Main] 验证 Cookie 失败:', verifyError);
  336. }
  337. return true;
  338. } catch (error) {
  339. console.error('[Main] 设置 cookies 失败:', error);
  340. return false;
  341. }
  342. });
  343. // 截取 webview 页面截图(用于 AI 分析)
  344. ipcMain.handle('capture-webview-page', async (_event: unknown, webContentsId: number) => {
  345. try {
  346. const wc = webContents.fromId(webContentsId);
  347. if (!wc) {
  348. console.error('找不到 webContents:', webContentsId);
  349. return null;
  350. }
  351. const image = await wc.capturePage();
  352. if (!image || image.isEmpty()) {
  353. console.warn('截图为空');
  354. return null;
  355. }
  356. // 转换为 JPEG 格式的 Base64
  357. const buffer = image.toJPEG(80);
  358. return buffer.toString('base64');
  359. } catch (error) {
  360. console.error('截图失败:', error);
  361. return null;
  362. }
  363. });
  364. // 向 webview 发送鼠标点击事件
  365. ipcMain.handle('webview-send-mouse-click', async (_event: unknown, webContentsId: number, x: number, y: number) => {
  366. try {
  367. const wc = webContents.fromId(webContentsId);
  368. if (!wc) {
  369. console.error('找不到 webContents:', webContentsId);
  370. return false;
  371. }
  372. // 发送鼠标移动事件
  373. wc.sendInputEvent({
  374. type: 'mouseMove',
  375. x: Math.round(x),
  376. y: Math.round(y),
  377. });
  378. // 短暂延迟后发送点击事件
  379. await new Promise(resolve => setTimeout(resolve, 50));
  380. // 发送鼠标按下事件
  381. wc.sendInputEvent({
  382. type: 'mouseDown',
  383. x: Math.round(x),
  384. y: Math.round(y),
  385. button: 'left',
  386. clickCount: 1,
  387. });
  388. // 短暂延迟后发送鼠标抬起事件
  389. await new Promise(resolve => setTimeout(resolve, 50));
  390. wc.sendInputEvent({
  391. type: 'mouseUp',
  392. x: Math.round(x),
  393. y: Math.round(y),
  394. button: 'left',
  395. clickCount: 1,
  396. });
  397. console.log(`[webview-send-mouse-click] Clicked at (${x}, ${y})`);
  398. return true;
  399. } catch (error) {
  400. console.error('发送点击事件失败:', error);
  401. return false;
  402. }
  403. });
  404. // 向 webview 发送键盘输入事件
  405. ipcMain.handle('webview-send-text-input', async (_event: unknown, webContentsId: number, text: string) => {
  406. try {
  407. const wc = webContents.fromId(webContentsId);
  408. if (!wc) {
  409. console.error('找不到 webContents:', webContentsId);
  410. return false;
  411. }
  412. // 逐字符输入
  413. for (const char of text) {
  414. wc.sendInputEvent({
  415. type: 'char',
  416. keyCode: char,
  417. });
  418. await new Promise(resolve => setTimeout(resolve, 30));
  419. }
  420. console.log(`[webview-send-text-input] Typed: ${text}`);
  421. return true;
  422. } catch (error) {
  423. console.error('发送输入事件失败:', error);
  424. return false;
  425. }
  426. });
  427. // 获取 webview 页面元素位置
  428. ipcMain.handle('webview-get-element-position', async (_event: unknown, webContentsId: number, selector: string) => {
  429. try {
  430. const wc = webContents.fromId(webContentsId);
  431. if (!wc) {
  432. console.error('找不到 webContents:', webContentsId);
  433. return null;
  434. }
  435. const result = await wc.executeJavaScript(`
  436. (function() {
  437. const el = document.querySelector('${selector.replace(/'/g, "\\'")}');
  438. if (!el) return null;
  439. const rect = el.getBoundingClientRect();
  440. return {
  441. x: rect.left + rect.width / 2,
  442. y: rect.top + rect.height / 2,
  443. width: rect.width,
  444. height: rect.height
  445. };
  446. })()
  447. `);
  448. return result;
  449. } catch (error) {
  450. console.error('获取元素位置失败:', error);
  451. return null;
  452. }
  453. });
  454. // 通过文本内容查找并点击元素
  455. ipcMain.handle('webview-click-by-text', async (_event: unknown, webContentsId: number, text: string) => {
  456. try {
  457. const wc = webContents.fromId(webContentsId);
  458. if (!wc) {
  459. console.error('找不到 webContents:', webContentsId);
  460. return false;
  461. }
  462. // 查找包含指定文本的可点击元素的位置
  463. const position = await wc.executeJavaScript(`
  464. (function() {
  465. const searchText = '${text.replace(/'/g, "\\'")}';
  466. // 查找可点击元素
  467. const clickables = document.querySelectorAll('a, button, [role="button"], [onclick], input[type="submit"], input[type="button"]');
  468. for (const el of clickables) {
  469. if (el.textContent?.includes(searchText) || el.getAttribute('aria-label')?.includes(searchText) || el.getAttribute('title')?.includes(searchText)) {
  470. const rect = el.getBoundingClientRect();
  471. if (rect.width > 0 && rect.height > 0) {
  472. return { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 };
  473. }
  474. }
  475. }
  476. // 查找所有包含文本的元素
  477. const allElements = document.querySelectorAll('*');
  478. for (const el of allElements) {
  479. const text = el.innerText?.trim();
  480. if (text && text.length < 100 && text.includes(searchText)) {
  481. const rect = el.getBoundingClientRect();
  482. if (rect.width > 0 && rect.height > 0 && rect.width < 500) {
  483. return { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 };
  484. }
  485. }
  486. }
  487. return null;
  488. })()
  489. `);
  490. if (!position) {
  491. console.warn(`[webview-click-by-text] 未找到包含 "${text}" 的元素`);
  492. return false;
  493. }
  494. // 发送点击事件
  495. wc.sendInputEvent({ type: 'mouseMove', x: Math.round(position.x), y: Math.round(position.y) });
  496. await new Promise(resolve => setTimeout(resolve, 50));
  497. wc.sendInputEvent({ type: 'mouseDown', x: Math.round(position.x), y: Math.round(position.y), button: 'left', clickCount: 1 });
  498. await new Promise(resolve => setTimeout(resolve, 50));
  499. wc.sendInputEvent({ type: 'mouseUp', x: Math.round(position.x), y: Math.round(position.y), button: 'left', clickCount: 1 });
  500. console.log(`[webview-click-by-text] Clicked "${text}" at (${position.x}, ${position.y})`);
  501. return true;
  502. } catch (error) {
  503. console.error('通过文本点击失败:', error);
  504. return false;
  505. }
  506. });
  507. // ========== CDP 网络拦截功能 ==========
  508. // 存储每个 webContents 的网络拦截配置
  509. const networkInterceptors: Map<number, {
  510. patterns: Array<{match: string, key: string}>;
  511. pendingRequests: Map<string, {url: string, timestamp: number}>;
  512. }> = new Map();
  513. // 启用 CDP 网络拦截
  514. ipcMain.handle('enable-network-intercept', async (_event: unknown, webContentsId: number, patterns: Array<{match: string, key: string}>) => {
  515. try {
  516. const wc = webContents.fromId(webContentsId);
  517. if (!wc) {
  518. console.error('[CDP] 找不到 webContents:', webContentsId);
  519. return false;
  520. }
  521. // 如果已经有拦截器,先清理
  522. if (networkInterceptors.has(webContentsId)) {
  523. try {
  524. wc.debugger.detach();
  525. } catch (e) {
  526. // 忽略
  527. }
  528. }
  529. // 存储配置
  530. networkInterceptors.set(webContentsId, {
  531. patterns,
  532. pendingRequests: new Map()
  533. });
  534. // 附加调试器
  535. try {
  536. wc.debugger.attach('1.3');
  537. } catch (err: unknown) {
  538. const error = err as Error;
  539. if (!error.message?.includes('Already attached')) {
  540. throw err;
  541. }
  542. }
  543. // 启用网络监听
  544. await wc.debugger.sendCommand('Network.enable');
  545. // 监听网络响应
  546. wc.debugger.on('message', async (_e: unknown, method: string, params: {
  547. requestId?: string;
  548. response?: { url?: string; status?: number; mimeType?: string };
  549. encodedDataLength?: number;
  550. }) => {
  551. const config = networkInterceptors.get(webContentsId);
  552. if (!config) return;
  553. if (method === 'Network.responseReceived') {
  554. const { requestId, response } = params;
  555. if (!requestId || !response?.url) return;
  556. // 调试:打印百家号相关的所有 API 请求
  557. if (response.url.includes('baijiahao.baidu.com')) {
  558. if (response.url.includes('/pcui/') || response.url.includes('/article')) {
  559. console.log(`[CDP DEBUG] 百家号 API: ${response.url}`);
  560. }
  561. }
  562. // 检查是否匹配我们关注的 API
  563. for (const pattern of config.patterns) {
  564. if (response.url.includes(pattern.match)) {
  565. // 记录请求,等待响应完成
  566. config.pendingRequests.set(requestId, {
  567. url: response.url,
  568. timestamp: Date.now()
  569. });
  570. console.log(`[CDP] 匹配到 API: ${pattern.key} - ${response.url}`);
  571. break;
  572. }
  573. }
  574. }
  575. if (method === 'Network.loadingFinished') {
  576. const { requestId } = params;
  577. if (!requestId) return;
  578. const pending = config.pendingRequests.get(requestId);
  579. if (!pending) return;
  580. config.pendingRequests.delete(requestId);
  581. try {
  582. // 获取响应体
  583. const result = await wc.debugger.sendCommand('Network.getResponseBody', { requestId }) as { body: string; base64Encoded: boolean };
  584. let body = result.body;
  585. // 如果是 base64 编码,解码
  586. if (result.base64Encoded) {
  587. body = Buffer.from(body, 'base64').toString('utf8');
  588. }
  589. // 解析 JSON
  590. const data = JSON.parse(body);
  591. // 找到匹配的 key
  592. let matchedKey = '';
  593. for (const pattern of config.patterns) {
  594. if (pending.url.includes(pattern.match)) {
  595. matchedKey = pattern.key;
  596. break;
  597. }
  598. }
  599. if (matchedKey) {
  600. console.log(`[CDP] 获取到响应: ${matchedKey}`, JSON.stringify(data).substring(0, 200));
  601. // 发送到渲染进程
  602. mainWindow?.webContents.send('network-intercept-data', {
  603. webContentsId,
  604. key: matchedKey,
  605. url: pending.url,
  606. data
  607. });
  608. }
  609. } catch (err) {
  610. console.warn(`[CDP] 获取响应体失败:`, err);
  611. }
  612. }
  613. });
  614. console.log(`[CDP] 已启用网络拦截,webContentsId: ${webContentsId}, patterns:`, patterns.map(p => p.key));
  615. return true;
  616. } catch (error) {
  617. console.error('[CDP] 启用网络拦截失败:', error);
  618. return false;
  619. }
  620. });
  621. // 禁用 CDP 网络拦截
  622. ipcMain.handle('disable-network-intercept', async (_event: unknown, webContentsId: number) => {
  623. try {
  624. const wc = webContents.fromId(webContentsId);
  625. if (wc) {
  626. try {
  627. wc.debugger.detach();
  628. } catch (e) {
  629. // 忽略
  630. }
  631. }
  632. networkInterceptors.delete(webContentsId);
  633. console.log(`[CDP] 已禁用网络拦截,webContentsId: ${webContentsId}`);
  634. return true;
  635. } catch (error) {
  636. console.error('[CDP] 禁用网络拦截失败:', error);
  637. return false;
  638. }
  639. });
  640. // 更新网络拦截的 patterns
  641. ipcMain.handle('update-network-patterns', async (_event: unknown, webContentsId: number, patterns: Array<{match: string, key: string}>) => {
  642. const config = networkInterceptors.get(webContentsId);
  643. if (config) {
  644. config.patterns = patterns;
  645. console.log(`[CDP] 已更新 patterns,webContentsId: ${webContentsId}`);
  646. return true;
  647. }
  648. return false;
  649. });