utils.js 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  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. chrome.runtime.sendMessage({
  231. type: 'CONTENT_SCRIPT_READY',
  232. source: SCRIPT_SOURCE,
  233. step: null,
  234. payload: {},
  235. error: null,
  236. });
  237. }
  238. /**
  239. * Report step completion.
  240. * @param {number} step
  241. * @param {Object} data - Step output data
  242. */
  243. function reportComplete(step, data = {}) {
  244. console.log(LOG_PREFIX, `步骤 ${step} 已完成`, data);
  245. log(`步骤 ${step} 已成功完成`, 'ok');
  246. chrome.runtime.sendMessage({
  247. type: 'STEP_COMPLETE',
  248. source: SCRIPT_SOURCE,
  249. step,
  250. payload: data,
  251. error: null,
  252. });
  253. }
  254. /**
  255. * Report step error.
  256. * @param {number} step
  257. * @param {string} errorMessage
  258. */
  259. function reportError(step, errorMessage) {
  260. console.error(LOG_PREFIX, `步骤 ${step} 失败: ${errorMessage}`);
  261. log(`步骤 ${step} 失败:${errorMessage}`, 'error');
  262. chrome.runtime.sendMessage({
  263. type: 'STEP_ERROR',
  264. source: SCRIPT_SOURCE,
  265. step,
  266. payload: {},
  267. error: errorMessage,
  268. });
  269. }
  270. /**
  271. * Simulate a click with proper event dispatching.
  272. * @param {Element} el
  273. */
  274. function simulateClick(el) {
  275. throwIfStopped();
  276. el.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true }));
  277. console.log(LOG_PREFIX, `已点击: ${el.tagName} ${el.textContent?.slice(0, 30) || ''}`);
  278. log(`已点击 [${el.tagName}] "${el.textContent?.trim().slice(0, 30) || ''}"`);
  279. }
  280. /**
  281. * Wait a specified number of milliseconds.
  282. * @param {number} ms
  283. * @returns {Promise<void>}
  284. */
  285. function sleep(ms) {
  286. return new Promise((resolve, reject) => {
  287. const start = Date.now();
  288. function tick() {
  289. if (flowStopped) {
  290. reject(new Error(STOP_ERROR_MESSAGE));
  291. return;
  292. }
  293. if (Date.now() - start >= ms) {
  294. resolve();
  295. return;
  296. }
  297. setTimeout(tick, Math.min(100, Math.max(25, ms - (Date.now() - start))));
  298. }
  299. tick();
  300. });
  301. }
  302. async function humanPause(min = 250, max = 850) {
  303. const duration = Math.floor(Math.random() * (max - min + 1)) + min;
  304. await sleep(duration);
  305. }
  306. // Auto-report ready on load
  307. // Skip ready signal from child iframes of mail pages to avoid overwriting the top frame's registration
  308. const _isMailChildFrame = (SCRIPT_SOURCE === 'qq-mail' || SCRIPT_SOURCE === 'mail-163' || SCRIPT_SOURCE === 'inbucket-mail') && window !== window.top;
  309. if (!_isMailChildFrame) {
  310. reportReady();
  311. }