utils.js 12 KB

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