utils.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  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. const message = {
  232. type: 'CONTENT_SCRIPT_READY',
  233. source: SCRIPT_SOURCE,
  234. step: null,
  235. payload: {},
  236. error: null,
  237. };
  238. Promise.resolve(chrome.runtime.sendMessage(message))
  239. .then((response) => {
  240. console.log(LOG_PREFIX, 'CONTENT_SCRIPT_READY sent successfully', { response, url: location.href });
  241. })
  242. .catch((err) => {
  243. console.error(LOG_PREFIX, 'CONTENT_SCRIPT_READY send failed', err?.message || err, { url: location.href });
  244. });
  245. }
  246. /**
  247. * Report step completion.
  248. * @param {number} step
  249. * @param {Object} data - Step output data
  250. */
  251. function reportComplete(step, data = {}) {
  252. console.log(LOG_PREFIX, `步骤 ${step} 已完成`, data);
  253. log(`步骤 ${step} 已成功完成`, 'ok');
  254. const message = {
  255. type: 'STEP_COMPLETE',
  256. source: SCRIPT_SOURCE,
  257. step,
  258. payload: data,
  259. error: null,
  260. };
  261. Promise.resolve(chrome.runtime.sendMessage(message))
  262. .then((response) => {
  263. console.log(LOG_PREFIX, `STEP_COMPLETE sent successfully for step ${step}`, {
  264. response,
  265. url: location.href,
  266. payloadKeys: Object.keys(data || {}),
  267. });
  268. })
  269. .catch((err) => {
  270. console.error(LOG_PREFIX, `STEP_COMPLETE send failed for step ${step}`, err?.message || err, {
  271. url: location.href,
  272. payloadKeys: Object.keys(data || {}),
  273. });
  274. });
  275. }
  276. /**
  277. * Report step error.
  278. * @param {number} step
  279. * @param {string} errorMessage
  280. */
  281. function reportError(step, errorMessage) {
  282. console.error(LOG_PREFIX, `步骤 ${step} 失败: ${errorMessage}`);
  283. log(`步骤 ${step} 失败:${errorMessage}`, 'error');
  284. const message = {
  285. type: 'STEP_ERROR',
  286. source: SCRIPT_SOURCE,
  287. step,
  288. payload: {},
  289. error: errorMessage,
  290. };
  291. Promise.resolve(chrome.runtime.sendMessage(message))
  292. .then((response) => {
  293. console.log(LOG_PREFIX, `STEP_ERROR sent successfully for step ${step}`, {
  294. response,
  295. url: location.href,
  296. errorMessage,
  297. });
  298. })
  299. .catch((err) => {
  300. console.error(LOG_PREFIX, `STEP_ERROR send failed for step ${step}`, err?.message || err, {
  301. url: location.href,
  302. errorMessage,
  303. });
  304. });
  305. }
  306. /**
  307. * Simulate a click with proper event dispatching.
  308. * @param {Element} el
  309. */
  310. function simulateClick(el) {
  311. throwIfStopped();
  312. if (!el) {
  313. throw new Error('无法点击空元素。');
  314. }
  315. const form = el.form || el.closest?.('form') || null;
  316. const strategy = typeof getActivationStrategy === 'function'
  317. ? getActivationStrategy({
  318. tagName: el.tagName,
  319. type: el.getAttribute?.('type') || el.type || '',
  320. hasForm: Boolean(form),
  321. pathname: location.pathname || '',
  322. })
  323. : { method: 'click' };
  324. let method = strategy.method || 'click';
  325. if (method === 'requestSubmit' && form && typeof form.requestSubmit === 'function') {
  326. form.requestSubmit(el);
  327. } else if (typeof el.click === 'function') {
  328. method = 'click';
  329. el.click();
  330. } else {
  331. method = 'dispatchEvent';
  332. el.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true }));
  333. }
  334. console.log(LOG_PREFIX, `已点击(${method}): ${el.tagName} ${el.textContent?.slice(0, 30) || ''}`);
  335. log(`已点击(${method}) [${el.tagName}] "${el.textContent?.trim().slice(0, 30) || ''}"`);
  336. }
  337. /**
  338. * Wait a specified number of milliseconds.
  339. * @param {number} ms
  340. * @returns {Promise<void>}
  341. */
  342. function sleep(ms) {
  343. return new Promise((resolve, reject) => {
  344. const start = Date.now();
  345. function tick() {
  346. if (flowStopped) {
  347. reject(new Error(STOP_ERROR_MESSAGE));
  348. return;
  349. }
  350. if (Date.now() - start >= ms) {
  351. resolve();
  352. return;
  353. }
  354. setTimeout(tick, Math.min(100, Math.max(25, ms - (Date.now() - start))));
  355. }
  356. tick();
  357. });
  358. }
  359. async function humanPause(min = 250, max = 850) {
  360. const duration = Math.floor(Math.random() * (max - min + 1)) + min;
  361. await sleep(duration);
  362. }
  363. // Auto-report ready on load
  364. // Skip ready signal from child iframes of mail pages to avoid overwriting the top frame's registration
  365. const _isMailChildFrame = (SCRIPT_SOURCE === 'qq-mail' || SCRIPT_SOURCE === 'mail-163' || SCRIPT_SOURCE === 'inbucket-mail') && window !== window.top;
  366. if (!_isMailChildFrame) {
  367. reportReady();
  368. }