main.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. "use strict";
  2. const { app, BrowserWindow, ipcMain, shell, session, Menu, Tray, nativeImage, webContents } = require("electron");
  3. const { join } = require("path");
  4. require("fs");
  5. let mainWindow = null;
  6. let tray = null;
  7. let isQuitting = false;
  8. const VITE_DEV_SERVER_URL = process.env.VITE_DEV_SERVER_URL;
  9. function getIconPath() {
  10. return VITE_DEV_SERVER_URL ? join(__dirname, "../public/icons/icon-256.png") : join(__dirname, "../dist/icons/icon-256.png");
  11. }
  12. function getTrayIconPath() {
  13. return VITE_DEV_SERVER_URL ? join(__dirname, "../public/icons/tray-icon.png") : join(__dirname, "../dist/icons/tray-icon.png");
  14. }
  15. function createTrayIcon() {
  16. const trayIconPath = getTrayIconPath();
  17. return nativeImage.createFromPath(trayIconPath);
  18. }
  19. function createTray() {
  20. const trayIcon = createTrayIcon();
  21. tray = new Tray(trayIcon);
  22. const contextMenu = Menu.buildFromTemplate([
  23. {
  24. label: "显示主窗口",
  25. click: () => {
  26. if (mainWindow) {
  27. mainWindow.show();
  28. mainWindow.focus();
  29. }
  30. }
  31. },
  32. {
  33. label: "最小化到托盘",
  34. click: () => {
  35. mainWindow == null ? void 0 : mainWindow.hide();
  36. }
  37. },
  38. { type: "separator" },
  39. {
  40. label: "退出",
  41. click: () => {
  42. isQuitting = true;
  43. app.quit();
  44. }
  45. }
  46. ]);
  47. tray.setToolTip("多平台媒体管理系统");
  48. tray.setContextMenu(contextMenu);
  49. tray.on("click", () => {
  50. if (mainWindow) {
  51. if (mainWindow.isVisible()) {
  52. mainWindow.focus();
  53. } else {
  54. mainWindow.show();
  55. mainWindow.focus();
  56. }
  57. }
  58. });
  59. tray.on("double-click", () => {
  60. if (mainWindow) {
  61. mainWindow.show();
  62. mainWindow.focus();
  63. }
  64. });
  65. }
  66. function createWindow() {
  67. Menu.setApplicationMenu(null);
  68. const iconPath = getIconPath();
  69. mainWindow = new BrowserWindow({
  70. width: 1400,
  71. height: 900,
  72. minWidth: 1200,
  73. minHeight: 700,
  74. icon: iconPath,
  75. webPreferences: {
  76. preload: join(__dirname, "preload.js"),
  77. nodeIntegration: false,
  78. contextIsolation: true,
  79. webviewTag: true
  80. // 启用 webview 标签
  81. },
  82. frame: false,
  83. // 无边框窗口,自定义标题栏
  84. transparent: false,
  85. backgroundColor: "#f0f2f5",
  86. show: false
  87. });
  88. mainWindow.once("ready-to-show", () => {
  89. mainWindow == null ? void 0 : mainWindow.show();
  90. setupWindowEvents();
  91. });
  92. if (VITE_DEV_SERVER_URL) {
  93. mainWindow.loadURL(VITE_DEV_SERVER_URL);
  94. mainWindow.webContents.openDevTools();
  95. } else {
  96. mainWindow.loadFile(join(__dirname, "../dist/index.html"));
  97. }
  98. mainWindow.webContents.setWindowOpenHandler(({ url }) => {
  99. shell.openExternal(url);
  100. return { action: "deny" };
  101. });
  102. mainWindow.on("close", (event) => {
  103. if (!isQuitting) {
  104. event.preventDefault();
  105. mainWindow == null ? void 0 : mainWindow.hide();
  106. if (tray && !app.isPackaged) ;
  107. }
  108. });
  109. mainWindow.on("closed", () => {
  110. mainWindow = null;
  111. });
  112. }
  113. const gotTheLock = app.requestSingleInstanceLock();
  114. if (!gotTheLock) {
  115. app.quit();
  116. } else {
  117. app.on("second-instance", () => {
  118. if (mainWindow) {
  119. mainWindow.show();
  120. if (mainWindow.isMinimized()) mainWindow.restore();
  121. mainWindow.focus();
  122. }
  123. });
  124. app.whenReady().then(() => {
  125. createTray();
  126. createWindow();
  127. setupWebviewSessions();
  128. app.on("activate", () => {
  129. if (BrowserWindow.getAllWindows().length === 0) {
  130. createWindow();
  131. } else if (mainWindow) {
  132. mainWindow.show();
  133. }
  134. });
  135. });
  136. }
  137. function setupWebviewSessions() {
  138. app.on("web-contents-created", (_event, contents) => {
  139. if (contents.getType() === "webview") {
  140. contents.setUserAgent(
  141. "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
  142. );
  143. contents.session.setPermissionRequestHandler((_webContents, permission, callback) => {
  144. callback(true);
  145. });
  146. contents.session.webRequest.onBeforeSendHeaders((details, callback) => {
  147. delete details.requestHeaders["X-DevTools-Emulate-Network-Conditions-Client-Id"];
  148. if (!details.requestHeaders["Origin"] && !details.requestHeaders["origin"]) ;
  149. callback({ requestHeaders: details.requestHeaders });
  150. });
  151. }
  152. });
  153. }
  154. app.on("window-all-closed", () => {
  155. });
  156. app.on("before-quit", () => {
  157. isQuitting = true;
  158. });
  159. app.on("quit", () => {
  160. if (tray) {
  161. tray.destroy();
  162. tray = null;
  163. }
  164. });
  165. ipcMain.handle("get-app-version", () => {
  166. return app.getVersion();
  167. });
  168. ipcMain.handle("get-platform", () => {
  169. return process.platform;
  170. });
  171. ipcMain.on("window-minimize", () => {
  172. mainWindow == null ? void 0 : mainWindow.minimize();
  173. });
  174. ipcMain.on("window-maximize", () => {
  175. if (mainWindow == null ? void 0 : mainWindow.isMaximized()) {
  176. mainWindow.unmaximize();
  177. } else {
  178. mainWindow == null ? void 0 : mainWindow.maximize();
  179. }
  180. });
  181. ipcMain.on("window-close", () => {
  182. mainWindow == null ? void 0 : mainWindow.hide();
  183. });
  184. ipcMain.on("app-quit", () => {
  185. isQuitting = true;
  186. app.quit();
  187. });
  188. ipcMain.handle("window-is-maximized", () => {
  189. return (mainWindow == null ? void 0 : mainWindow.isMaximized()) || false;
  190. });
  191. function setupWindowEvents() {
  192. mainWindow == null ? void 0 : mainWindow.on("maximize", () => {
  193. mainWindow == null ? void 0 : mainWindow.webContents.send("window-maximized", true);
  194. });
  195. mainWindow == null ? void 0 : mainWindow.on("unmaximize", () => {
  196. mainWindow == null ? void 0 : mainWindow.webContents.send("window-maximized", false);
  197. });
  198. }
  199. ipcMain.handle("get-webview-cookies", async (_event, partition, url) => {
  200. try {
  201. const ses = session.fromPartition(partition);
  202. const cookies = await ses.cookies.get({ url });
  203. return cookies;
  204. } catch (error) {
  205. console.error("获取 cookies 失败:", error);
  206. return [];
  207. }
  208. });
  209. ipcMain.handle("clear-webview-cookies", async (_event, partition) => {
  210. try {
  211. const ses = session.fromPartition(partition);
  212. await ses.clearStorageData({ storages: ["cookies"] });
  213. return true;
  214. } catch (error) {
  215. console.error("清除 cookies 失败:", error);
  216. return false;
  217. }
  218. });
  219. ipcMain.handle("set-webview-cookies", async (_event, partition, cookies) => {
  220. try {
  221. const ses = session.fromPartition(partition);
  222. for (const cookie of cookies) {
  223. await ses.cookies.set(cookie);
  224. }
  225. return true;
  226. } catch (error) {
  227. console.error("设置 cookies 失败:", error);
  228. return false;
  229. }
  230. });
  231. ipcMain.handle("capture-webview-page", async (_event, webContentsId) => {
  232. try {
  233. const wc = webContents.fromId(webContentsId);
  234. if (!wc) {
  235. console.error("找不到 webContents:", webContentsId);
  236. return null;
  237. }
  238. const image = await wc.capturePage();
  239. if (!image || image.isEmpty()) {
  240. console.warn("截图为空");
  241. return null;
  242. }
  243. const buffer = image.toJPEG(80);
  244. return buffer.toString("base64");
  245. } catch (error) {
  246. console.error("截图失败:", error);
  247. return null;
  248. }
  249. });
  250. ipcMain.handle("webview-send-mouse-click", async (_event, webContentsId, x, y) => {
  251. try {
  252. const wc = webContents.fromId(webContentsId);
  253. if (!wc) {
  254. console.error("找不到 webContents:", webContentsId);
  255. return false;
  256. }
  257. wc.sendInputEvent({
  258. type: "mouseMove",
  259. x: Math.round(x),
  260. y: Math.round(y)
  261. });
  262. await new Promise((resolve) => setTimeout(resolve, 50));
  263. wc.sendInputEvent({
  264. type: "mouseDown",
  265. x: Math.round(x),
  266. y: Math.round(y),
  267. button: "left",
  268. clickCount: 1
  269. });
  270. await new Promise((resolve) => setTimeout(resolve, 50));
  271. wc.sendInputEvent({
  272. type: "mouseUp",
  273. x: Math.round(x),
  274. y: Math.round(y),
  275. button: "left",
  276. clickCount: 1
  277. });
  278. console.log(`[webview-send-mouse-click] Clicked at (${x}, ${y})`);
  279. return true;
  280. } catch (error) {
  281. console.error("发送点击事件失败:", error);
  282. return false;
  283. }
  284. });
  285. ipcMain.handle("webview-send-text-input", async (_event, webContentsId, text) => {
  286. try {
  287. const wc = webContents.fromId(webContentsId);
  288. if (!wc) {
  289. console.error("找不到 webContents:", webContentsId);
  290. return false;
  291. }
  292. for (const char of text) {
  293. wc.sendInputEvent({
  294. type: "char",
  295. keyCode: char
  296. });
  297. await new Promise((resolve) => setTimeout(resolve, 30));
  298. }
  299. console.log(`[webview-send-text-input] Typed: ${text}`);
  300. return true;
  301. } catch (error) {
  302. console.error("发送输入事件失败:", error);
  303. return false;
  304. }
  305. });
  306. ipcMain.handle("webview-get-element-position", async (_event, webContentsId, selector) => {
  307. try {
  308. const wc = webContents.fromId(webContentsId);
  309. if (!wc) {
  310. console.error("找不到 webContents:", webContentsId);
  311. return null;
  312. }
  313. const result = await wc.executeJavaScript(`
  314. (function() {
  315. const el = document.querySelector('${selector.replace(/'/g, "\\'")}');
  316. if (!el) return null;
  317. const rect = el.getBoundingClientRect();
  318. return {
  319. x: rect.left + rect.width / 2,
  320. y: rect.top + rect.height / 2,
  321. width: rect.width,
  322. height: rect.height
  323. };
  324. })()
  325. `);
  326. return result;
  327. } catch (error) {
  328. console.error("获取元素位置失败:", error);
  329. return null;
  330. }
  331. });
  332. ipcMain.handle("webview-click-by-text", async (_event, webContentsId, text) => {
  333. try {
  334. const wc = webContents.fromId(webContentsId);
  335. if (!wc) {
  336. console.error("找不到 webContents:", webContentsId);
  337. return false;
  338. }
  339. const position = await wc.executeJavaScript(`
  340. (function() {
  341. const searchText = '${text.replace(/'/g, "\\'")}';
  342. // 查找可点击元素
  343. const clickables = document.querySelectorAll('a, button, [role="button"], [onclick], input[type="submit"], input[type="button"]');
  344. for (const el of clickables) {
  345. if (el.textContent?.includes(searchText) || el.getAttribute('aria-label')?.includes(searchText) || el.getAttribute('title')?.includes(searchText)) {
  346. const rect = el.getBoundingClientRect();
  347. if (rect.width > 0 && rect.height > 0) {
  348. return { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 };
  349. }
  350. }
  351. }
  352. // 查找所有包含文本的元素
  353. const allElements = document.querySelectorAll('*');
  354. for (const el of allElements) {
  355. const text = el.innerText?.trim();
  356. if (text && text.length < 100 && text.includes(searchText)) {
  357. const rect = el.getBoundingClientRect();
  358. if (rect.width > 0 && rect.height > 0 && rect.width < 500) {
  359. return { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 };
  360. }
  361. }
  362. }
  363. return null;
  364. })()
  365. `);
  366. if (!position) {
  367. console.warn(`[webview-click-by-text] 未找到包含 "${text}" 的元素`);
  368. return false;
  369. }
  370. wc.sendInputEvent({ type: "mouseMove", x: Math.round(position.x), y: Math.round(position.y) });
  371. await new Promise((resolve) => setTimeout(resolve, 50));
  372. wc.sendInputEvent({ type: "mouseDown", x: Math.round(position.x), y: Math.round(position.y), button: "left", clickCount: 1 });
  373. await new Promise((resolve) => setTimeout(resolve, 50));
  374. wc.sendInputEvent({ type: "mouseUp", x: Math.round(position.x), y: Math.round(position.y), button: "left", clickCount: 1 });
  375. console.log(`[webview-click-by-text] Clicked "${text}" at (${position.x}, ${position.y})`);
  376. return true;
  377. } catch (error) {
  378. console.error("通过文本点击失败:", error);
  379. return false;
  380. }
  381. });
  382. //# sourceMappingURL=main.js.map