utils.js 10 KB

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