utils.js 12 KB

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