utils.js 12 KB

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