utils.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. // content/utils.js — Shared utilities for all content scripts
  2. const SCRIPT_SOURCE = (() => {
  3. if (window.__MULTIPAGE_SOURCE) return window.__MULTIPAGE_SOURCE;
  4. const url = location.href;
  5. const hostname = location.hostname;
  6. if (url.includes('auth0.openai.com') || url.includes('auth.openai.com') || url.includes('accounts.openai.com')) return 'signup-page';
  7. if (hostname === 'mail.qq.com' || hostname === 'wx.mail.qq.com') return 'qq-mail';
  8. if (hostname === 'mail.163.com' || hostname.endsWith('.mail.163.com') || hostname === 'webmail.vip.163.com') return 'mail-163';
  9. if (url.includes('duckduckgo.com/email/settings/autofill')) return 'duck-mail';
  10. if (url.includes('chatgpt.com')) return 'chatgpt';
  11. // VPS panel — detected dynamically since URL is configurable
  12. return 'vps-panel';
  13. })();
  14. const LOG_PREFIX = `[MultiPage:${SCRIPT_SOURCE}]`;
  15. const STOP_ERROR_MESSAGE = '流程已被用户停止。';
  16. let flowStopped = false;
  17. if (!window.__MULTIPAGE_UTILS_LISTENER_READY__) {
  18. window.__MULTIPAGE_UTILS_LISTENER_READY__ = true;
  19. chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  20. if (message.type === 'STOP_FLOW') {
  21. flowStopped = true;
  22. console.warn(LOG_PREFIX, STOP_ERROR_MESSAGE);
  23. return;
  24. }
  25. if (message.type === 'PING') {
  26. sendResponse({
  27. ok: true,
  28. source: SCRIPT_SOURCE,
  29. });
  30. }
  31. });
  32. }
  33. function resetStopState() {
  34. flowStopped = false;
  35. }
  36. function isStopError(error) {
  37. const message = typeof error === 'string' ? error : error?.message;
  38. return message === STOP_ERROR_MESSAGE;
  39. }
  40. function throwIfStopped() {
  41. if (flowStopped) {
  42. throw new Error(STOP_ERROR_MESSAGE);
  43. }
  44. }
  45. /**
  46. * Wait for a DOM element to appear.
  47. * @param {string} selector - CSS selector
  48. * @param {number} timeout - Max wait time in ms (default 10000)
  49. * @returns {Promise<Element>}
  50. */
  51. function waitForElement(selector, timeout = 10000) {
  52. return new Promise((resolve, reject) => {
  53. throwIfStopped();
  54. const existing = document.querySelector(selector);
  55. if (existing) {
  56. console.log(LOG_PREFIX, `立即找到元素: ${selector}`);
  57. log(`已找到元素:${selector}`);
  58. resolve(existing);
  59. return;
  60. }
  61. console.log(LOG_PREFIX, `等待元素: ${selector}(超时 ${timeout}ms)`);
  62. log(`正在等待选择器:${selector}...`);
  63. let settled = false;
  64. let stopTimer = null;
  65. const cleanup = () => {
  66. if (settled) return;
  67. settled = true;
  68. observer.disconnect();
  69. clearTimeout(timer);
  70. clearTimeout(stopTimer);
  71. };
  72. const observer = new MutationObserver(() => {
  73. if (flowStopped) {
  74. cleanup();
  75. reject(new Error(STOP_ERROR_MESSAGE));
  76. return;
  77. }
  78. const el = document.querySelector(selector);
  79. if (el) {
  80. cleanup();
  81. console.log(LOG_PREFIX, `等待后找到元素: ${selector}`);
  82. log(`已找到元素:${selector}`);
  83. resolve(el);
  84. }
  85. });
  86. observer.observe(document.body || document.documentElement, {
  87. childList: true,
  88. subtree: true,
  89. });
  90. const timer = setTimeout(() => {
  91. cleanup();
  92. const msg = `在 ${location.href} 等待 ${selector} 超时,已超过 ${timeout}ms`;
  93. console.error(LOG_PREFIX, msg);
  94. reject(new Error(msg));
  95. }, timeout);
  96. const pollStop = () => {
  97. if (settled) return;
  98. if (flowStopped) {
  99. cleanup();
  100. reject(new Error(STOP_ERROR_MESSAGE));
  101. return;
  102. }
  103. stopTimer = setTimeout(pollStop, 100);
  104. };
  105. pollStop();
  106. });
  107. }
  108. /**
  109. * Wait for an element matching a text pattern among multiple candidates.
  110. * @param {string} containerSelector - Selector for candidate elements
  111. * @param {RegExp} textPattern - Regex to match against textContent
  112. * @param {number} timeout - Max wait time in ms
  113. * @returns {Promise<Element>}
  114. */
  115. function waitForElementByText(containerSelector, textPattern, timeout = 10000) {
  116. return new Promise((resolve, reject) => {
  117. throwIfStopped();
  118. function search() {
  119. const candidates = document.querySelectorAll(containerSelector);
  120. for (const el of candidates) {
  121. if (textPattern.test(el.textContent)) {
  122. return el;
  123. }
  124. }
  125. return null;
  126. }
  127. const existing = search();
  128. if (existing) {
  129. console.log(LOG_PREFIX, `立即按文本找到元素: ${containerSelector} 匹配 ${textPattern}`);
  130. log(`已按文本找到元素:${textPattern}`);
  131. resolve(existing);
  132. return;
  133. }
  134. console.log(LOG_PREFIX, `等待文本匹配: ${containerSelector} / ${textPattern}`);
  135. log(`正在等待包含文本的元素:${textPattern}...`);
  136. let settled = false;
  137. let stopTimer = null;
  138. const cleanup = () => {
  139. if (settled) return;
  140. settled = true;
  141. observer.disconnect();
  142. clearTimeout(timer);
  143. clearTimeout(stopTimer);
  144. };
  145. const observer = new MutationObserver(() => {
  146. if (flowStopped) {
  147. cleanup();
  148. reject(new Error(STOP_ERROR_MESSAGE));
  149. return;
  150. }
  151. const el = search();
  152. if (el) {
  153. cleanup();
  154. console.log(LOG_PREFIX, `等待后按文本找到元素: ${textPattern}`);
  155. log(`已按文本找到元素:${textPattern}`);
  156. resolve(el);
  157. }
  158. });
  159. observer.observe(document.body || document.documentElement, {
  160. childList: true,
  161. subtree: true,
  162. });
  163. const timer = setTimeout(() => {
  164. cleanup();
  165. const msg = `在 ${location.href} 的 ${containerSelector} 中等待文本 "${textPattern}" 超时,已超过 ${timeout}ms`;
  166. console.error(LOG_PREFIX, msg);
  167. reject(new Error(msg));
  168. }, timeout);
  169. const pollStop = () => {
  170. if (settled) return;
  171. if (flowStopped) {
  172. cleanup();
  173. reject(new Error(STOP_ERROR_MESSAGE));
  174. return;
  175. }
  176. stopTimer = setTimeout(pollStop, 100);
  177. };
  178. pollStop();
  179. });
  180. }
  181. /**
  182. * React-compatible form filling.
  183. * Sets value via native setter and dispatches input + change events.
  184. * @param {HTMLInputElement} el
  185. * @param {string} value
  186. */
  187. function fillInput(el, value) {
  188. throwIfStopped();
  189. const nativeInputValueSetter = Object.getOwnPropertyDescriptor(
  190. window.HTMLInputElement.prototype,
  191. 'value'
  192. ).set;
  193. nativeInputValueSetter.call(el, value);
  194. el.dispatchEvent(new Event('input', { bubbles: true }));
  195. el.dispatchEvent(new Event('change', { bubbles: true }));
  196. console.log(LOG_PREFIX, `已填写输入框 ${el.name || el.id || el.type}: ${value}`);
  197. log(`已填写输入框 [${el.name || el.id || el.type || '未知'}]`);
  198. }
  199. /**
  200. * Fill a select element by setting its value and triggering change.
  201. * @param {HTMLSelectElement} el
  202. * @param {string} value
  203. */
  204. function fillSelect(el, value) {
  205. throwIfStopped();
  206. el.value = value;
  207. el.dispatchEvent(new Event('change', { bubbles: true }));
  208. console.log(LOG_PREFIX, `已在 ${el.name || el.id} 中选择值: ${value}`);
  209. log(`已选择 [${el.name || el.id || '未知'}] = ${value}`);
  210. }
  211. /**
  212. * Send a log message to Side Panel via Background.
  213. * @param {string} message
  214. * @param {string} level - 'info' | 'ok' | 'warn' | 'error'
  215. */
  216. function log(message, level = 'info') {
  217. chrome.runtime.sendMessage({
  218. type: 'LOG',
  219. source: SCRIPT_SOURCE,
  220. step: null,
  221. payload: { message, level, timestamp: Date.now() },
  222. error: null,
  223. });
  224. }
  225. /**
  226. * Report that this content script is loaded and ready.
  227. */
  228. function reportReady() {
  229. console.log(LOG_PREFIX, '内容脚本已就绪');
  230. const message = {
  231. type: 'CONTENT_SCRIPT_READY',
  232. source: SCRIPT_SOURCE,
  233. step: null,
  234. payload: {},
  235. error: null,
  236. };
  237. Promise.resolve(chrome.runtime.sendMessage(message))
  238. .then((response) => {
  239. console.log(LOG_PREFIX, 'CONTENT_SCRIPT_READY sent successfully', { response, url: location.href });
  240. })
  241. .catch((err) => {
  242. console.error(LOG_PREFIX, 'CONTENT_SCRIPT_READY send failed', err?.message || err, { url: location.href });
  243. });
  244. }
  245. /**
  246. * Report step completion.
  247. * @param {number} step
  248. * @param {Object} data - Step output data
  249. */
  250. function reportComplete(step, data = {}) {
  251. console.log(LOG_PREFIX, `步骤 ${step} 已完成`, data);
  252. log(`步骤 ${step} 已成功完成`, 'ok');
  253. const message = {
  254. type: 'STEP_COMPLETE',
  255. source: SCRIPT_SOURCE,
  256. step,
  257. payload: data,
  258. error: null,
  259. };
  260. Promise.resolve(chrome.runtime.sendMessage(message))
  261. .then((response) => {
  262. console.log(LOG_PREFIX, `STEP_COMPLETE sent successfully for step ${step}`, {
  263. response,
  264. url: location.href,
  265. payloadKeys: Object.keys(data || {}),
  266. });
  267. })
  268. .catch((err) => {
  269. console.error(LOG_PREFIX, `STEP_COMPLETE send failed for step ${step}`, err?.message || err, {
  270. url: location.href,
  271. payloadKeys: Object.keys(data || {}),
  272. });
  273. });
  274. }
  275. /**
  276. * Report step error.
  277. * @param {number} step
  278. * @param {string} errorMessage
  279. */
  280. function reportError(step, errorMessage) {
  281. console.error(LOG_PREFIX, `步骤 ${step} 失败: ${errorMessage}`);
  282. log(`步骤 ${step} 失败:${errorMessage}`, 'error');
  283. const message = {
  284. type: 'STEP_ERROR',
  285. source: SCRIPT_SOURCE,
  286. step,
  287. payload: {},
  288. error: errorMessage,
  289. };
  290. Promise.resolve(chrome.runtime.sendMessage(message))
  291. .then((response) => {
  292. console.log(LOG_PREFIX, `STEP_ERROR sent successfully for step ${step}`, {
  293. response,
  294. url: location.href,
  295. errorMessage,
  296. });
  297. })
  298. .catch((err) => {
  299. console.error(LOG_PREFIX, `STEP_ERROR send failed for step ${step}`, err?.message || err, {
  300. url: location.href,
  301. errorMessage,
  302. });
  303. });
  304. }
  305. /**
  306. * Simulate a click with proper event dispatching.
  307. * @param {Element} el
  308. */
  309. function simulateClick(el) {
  310. throwIfStopped();
  311. el.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true }));
  312. console.log(LOG_PREFIX, `已点击: ${el.tagName} ${el.textContent?.slice(0, 30) || ''}`);
  313. log(`已点击 [${el.tagName}] "${el.textContent?.trim().slice(0, 30) || ''}"`);
  314. }
  315. /**
  316. * Wait a specified number of milliseconds.
  317. * @param {number} ms
  318. * @returns {Promise<void>}
  319. */
  320. function sleep(ms) {
  321. return new Promise((resolve, reject) => {
  322. const start = Date.now();
  323. function tick() {
  324. if (flowStopped) {
  325. reject(new Error(STOP_ERROR_MESSAGE));
  326. return;
  327. }
  328. if (Date.now() - start >= ms) {
  329. resolve();
  330. return;
  331. }
  332. setTimeout(tick, Math.min(100, Math.max(25, ms - (Date.now() - start))));
  333. }
  334. tick();
  335. });
  336. }
  337. async function humanPause(min = 250, max = 850) {
  338. const duration = Math.floor(Math.random() * (max - min + 1)) + min;
  339. await sleep(duration);
  340. }
  341. // Auto-report ready on load
  342. // Skip ready signal from child iframes of mail pages to avoid overwriting the top frame's registration
  343. const _isMailChildFrame = (SCRIPT_SOURCE === 'qq-mail' || SCRIPT_SOURCE === 'mail-163' || SCRIPT_SOURCE === 'inbucket-mail') && window !== window.top;
  344. if (!_isMailChildFrame) {
  345. reportReady();
  346. }