utils.js 12 KB

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