content.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628
  1. /**
  2. * 侧边栏管理类
  3. */
  4. class SidebarManager {
  5. /**
  6. * @constant {Object} 配置常量
  7. */
  8. static CONFIG = {
  9. SIDEBAR_ID: "paiwise-sidebar",
  10. WRAPPER_ID: "paiwise-main-wrapper",
  11. STORAGE_KEY: "sidebarOpen",
  12. };
  13. constructor() {
  14. this.sidebarId = SidebarManager.CONFIG.SIDEBAR_ID;
  15. this.wrapperId = SidebarManager.CONFIG.WRAPPER_ID;
  16. this.isOpen = false;
  17. this.currentUrl = window.location.href;
  18. this.currentTitle = document.title;
  19. this.init();
  20. }
  21. /**
  22. * 初始化侧边栏
  23. */
  24. async init() {
  25. try {
  26. await this.checkAndRestoreState();
  27. this.setupEventListeners();
  28. } catch (error) {
  29. console.error("Sidebar initialization failed:", error);
  30. }
  31. }
  32. /**
  33. * 设置事件监听器
  34. */
  35. setupEventListeners() {
  36. // 监听页面加载完成事件
  37. window.addEventListener("load", () => this.checkAndRestoreState());
  38. // 监听来自 sidebar 的消息
  39. window.addEventListener("message", this.handleMessage.bind(this));
  40. // 监听窗口大小变化
  41. window.addEventListener(
  42. "resize",
  43. Utils.debounce(() => this.handleResize(), 100)
  44. );
  45. // 监听页面可见性变化
  46. document.addEventListener("visibilitychange", () => {
  47. if (!document.hidden) {
  48. this.checkAndRestoreState();
  49. }
  50. });
  51. // 监听 history 变化
  52. window.addEventListener("popstate", () => {
  53. this.checkAndRestoreState();
  54. });
  55. // 监听标题变化
  56. const titleObserver = new MutationObserver(() => {
  57. if (document.title !== this.currentTitle) {
  58. this.currentTitle = document.title;
  59. this.updatePageInfo();
  60. }
  61. });
  62. titleObserver.observe(
  63. document.querySelector("head > title") || document.head,
  64. {
  65. subtree: true,
  66. characterData: true,
  67. childList: true,
  68. }
  69. );
  70. const simulateUserInput = async (element, value) => {
  71. // 设置值
  72. // if (element.tagName.toLowerCase() === 'textarea') {
  73. // element.focus()
  74. // element.value = value
  75. // element.blur()
  76. // return
  77. // }
  78. element.value = value;
  79. // 创建并触发 input 事件
  80. const inputEvent = new Event('input', { bubbles: true });
  81. element.dispatchEvent(inputEvent);
  82. // 创建并触发 change 事件
  83. const changeEvent = new Event('change', { bubbles: true });
  84. element.dispatchEvent(changeEvent);
  85. // 可选:如果表单使用了 React/Vue 等框架,可能还需要触发以下事件
  86. element.dispatchEvent(new Event('blur'));
  87. element.dispatchEvent(new KeyboardEvent('keyup', { key: 'Enter' }));
  88. }
  89. const findLabelForInput = (label) => {
  90. let p = label.parentElement
  91. for (let i = 0; i < 10; i++) {
  92. const input = p.getElementsByTagName('input')
  93. if (input.length > 0) {
  94. return input[0]
  95. }
  96. p = p.parentElement
  97. }
  98. return null
  99. }
  100. const findLabelForSpan = (label) => {
  101. let p = label.parentElement
  102. for (let i = 0; i < 10; i++) {
  103. const span = p.getElementsByTagName('span')
  104. if (span.length > 0) {
  105. return [...span]
  106. }
  107. p = p.parentElement
  108. }
  109. return null
  110. }
  111. // 监听页面 URL 变化
  112. new MutationObserver(() => {
  113. const url = location.href;
  114. if (url !== this.currentUrl) {
  115. this.currentUrl = url;
  116. this.updatePageInfo();
  117. this.checkAndRestoreState();
  118. }
  119. }).observe(document, { subtree: true, childList: true });
  120. const handleFillInput = async (data, index) => {
  121. for (let i = 0; i < data.length; i++) {
  122. const item = data[i]
  123. if (item.findBy === 'id') {
  124. const input = formChildren.find(child => child.id === item.findByValue)
  125. if (item.type === 'text' || item.type === 'textarea' || item.type === 'number') {
  126. if (!input) {
  127. if (item.label) {
  128. const label = [...form.getElementsByTagName('label')].find(label => label.innerText.includes(item.label))
  129. if (label) {
  130. const input = findLabelForInput(label)
  131. if (input) {
  132. await simulateUserInput(input, excelDataA[item.excelColumn][index])
  133. }
  134. }
  135. }
  136. }
  137. if (input) {
  138. await simulateUserInput(input, excelDataA[item.excelColumn][index])
  139. }
  140. }
  141. if (item.type === 'radio' || item.type === 'checkbox') {
  142. if (item.label) {
  143. const label = [...form.getElementsByTagName('label')].find(label => label.innerText.includes(item.label))
  144. if (label) {
  145. const span = findLabelForSpan(label)
  146. span.forEach(span => {
  147. span.innerText === excelDataA[item.excelColumn][index] && span.click()
  148. })
  149. }
  150. }
  151. }
  152. if (item.type === 'date') {
  153. const input = formChildren.find(child => child.id === item.findByValue)
  154. if (excelDataA[item.excelColumn][index]) {
  155. await simulateCompleteUserAction(input, input, excelDataA[item.excelColumn][index], excelDataA[item.excelColumn][index])
  156. }
  157. }
  158. } else if (item.findBy === 'placeholder') {
  159. const input = formChildren.find(child => child.placeholder === item.findByValue)
  160. if (input) {
  161. simulateUserInput(input, excelDataA[item.excelColumn][index])
  162. }
  163. }
  164. }
  165. }
  166. let form = null
  167. let formChildren = []
  168. let excelDataA = []
  169. // 监听来自sidebar的消息
  170. window.addEventListener("message", async (event) => {
  171. if (event.data.type === "COPY_TO_CLIPBOARD") {
  172. try {
  173. await navigator.clipboard.writeText(event.data.text);
  174. // 可选:发送成功消息回sidebar
  175. event.source.postMessage(
  176. {
  177. type: "COPY_SUCCESS",
  178. },
  179. "*"
  180. );
  181. } catch (err) {
  182. console.error("Failed to copy text:", err);
  183. // 可选:发送失败消息回sidebar
  184. event.source.postMessage(
  185. {
  186. type: "COPY_ERROR",
  187. error: err.message,
  188. },
  189. "*"
  190. );
  191. }
  192. }
  193. if (event.data.type === "HANDLE_FILL_INPUT") {
  194. const { formData, excelData } = event.data.data
  195. excelDataA = excelData
  196. console.log(formChildren, excelDataA);
  197. await handleFillInput(formData, 0)
  198. }
  199. });
  200. // 监听来自iframe的消息
  201. window.addEventListener("message", (event) => {
  202. // 确保消息来自我们的iframe
  203. if (
  204. event.source ===
  205. document.getElementById("paiwise-sidebar")?.contentWindow
  206. ) {
  207. if (event.data.type === "FILL_INPUT") {
  208. event.source.postMessage(
  209. {
  210. type: "GE_T",
  211. pageInfo: pageInfo,
  212. },
  213. "*"
  214. );
  215. }
  216. if (event.data.type === "ANALYZE_PAGE") {
  217. form = document.querySelectorAll("form")[1];
  218. formChildren = [...form.elements]
  219. // 分析页面并返回结果
  220. const pageInfo = window.pageAnalyzer.analyzePage();
  221. // 发送分析结果回iframe
  222. event.source.postMessage(
  223. {
  224. type: "PAGE_ANALYSIS_RESULT",
  225. pageInfo: form.outerHTML,
  226. },
  227. "*"
  228. );
  229. }
  230. }
  231. });
  232. }
  233. handleUserName(input) {
  234. return input.placeholder.includes('账号') || input.placeholder.includes('用户名')
  235. }
  236. /**
  237. * 处理接收到的消息
  238. * @param {MessageEvent} event
  239. */
  240. handleMessage(event) {
  241. if (event.data.action === "closeSidebar") {
  242. this.removeSidebar();
  243. }
  244. }
  245. /**
  246. * 处理窗口大小变化
  247. */
  248. handleResize() {
  249. const sidebar = document.getElementById(this.sidebarId);
  250. if (sidebar && this.isOpen) {
  251. sidebar.style.height = `${window.innerHeight}px`;
  252. }
  253. }
  254. /**
  255. * 检查并恢复侧边栏状态
  256. */
  257. async checkAndRestoreState() {
  258. try {
  259. const isOpen = await Utils.getStorageData(
  260. SidebarManager.CONFIG.STORAGE_KEY
  261. );
  262. if (isOpen && !this.isOpen) {
  263. // 只有当应该打开且当前未打开时才创建
  264. this.createSidebar();
  265. } else if (!isOpen && this.isOpen) {
  266. // 只有当应该关闭且当前打开时才移除
  267. this.removeSidebar();
  268. }
  269. } catch (error) {
  270. console.error("Failed to restore sidebar state:", error);
  271. }
  272. }
  273. /**
  274. * 包装页面内容
  275. */
  276. wrapPageContent() {
  277. if (document.getElementById(this.wrapperId)) return;
  278. const wrapper = document.createElement("div");
  279. wrapper.id = this.wrapperId;
  280. // 保存body的原始样式
  281. this.originalBodyStyle = {
  282. width: document.body.style.width,
  283. margin: document.body.style.margin,
  284. position: document.body.style.position,
  285. overflow: document.body.style.overflow,
  286. };
  287. // 包装内容
  288. while (document.body.firstChild) {
  289. if (document.body.firstChild.id !== this.sidebarId) {
  290. wrapper.appendChild(document.body.firstChild);
  291. } else {
  292. document.body.removeChild(document.body.firstChild);
  293. }
  294. }
  295. document.body.appendChild(wrapper);
  296. }
  297. /**
  298. * 解除页面内容包装
  299. */
  300. unwrapPageContent() {
  301. const wrapper = document.getElementById(this.wrapperId);
  302. if (!wrapper) return;
  303. // 恢复body的原始样式
  304. if (this.originalBodyStyle) {
  305. Object.assign(document.body.style, this.originalBodyStyle);
  306. }
  307. while (wrapper.firstChild) {
  308. document.body.insertBefore(wrapper.firstChild, wrapper);
  309. }
  310. wrapper.remove();
  311. }
  312. /**
  313. * 发送页面信息到iframe
  314. */
  315. sendPageInfo() {
  316. this.updatePageInfo();
  317. }
  318. /**
  319. * 更新页面信息
  320. */
  321. updatePageInfo() {
  322. const iframe = document.getElementById(this.sidebarId);
  323. if (!iframe) return;
  324. // 获取最新的favicon
  325. const favicon = this.getFavicon();
  326. // 发送更新后的页面信息
  327. iframe.contentWindow.postMessage(
  328. {
  329. type: "PAGE_INFO",
  330. pageInfo: {
  331. favicon,
  332. title: document.title,
  333. url: window.location.href,
  334. iframe: window.pageAnalyzer.analyzePage()
  335. },
  336. },
  337. "*"
  338. );
  339. }
  340. /**
  341. * 获取最新的favicon
  342. */
  343. getFavicon() {
  344. // 尝试获取动态favicon
  345. const iconLinks = Array.from(
  346. document.querySelectorAll('link[rel*="icon"]')
  347. );
  348. const favicon = iconLinks
  349. .sort((a, b) => {
  350. // 优先使用大尺寸图标
  351. const sizeA = parseInt(a.sizes?.value) || 0;
  352. const sizeB = parseInt(b.sizes?.value) || 0;
  353. return sizeB - sizeA;
  354. })
  355. .map((link) => link.href)
  356. .find(Boolean);
  357. if (favicon) return favicon;
  358. // 如果没有找到,返回网站根目录的favicon.ico
  359. const url = new URL(window.location.href);
  360. return `${url.protocol}//${url.hostname}/favicon.ico`;
  361. }
  362. /**
  363. * 创建侧边栏
  364. */
  365. async createSidebar() {
  366. if (document.getElementById(this.sidebarId)) return;
  367. try {
  368. this.wrapPageContent();
  369. const iframe = document.createElement("iframe");
  370. iframe.id = this.sidebarId;
  371. iframe.src = chrome.runtime.getURL("sidebar.html");
  372. // 先添加到DOM,但不添加show类
  373. document.body.appendChild(iframe);
  374. // 等待iframe加载完成
  375. await new Promise((resolve) => {
  376. iframe.onload = () => {
  377. // 发送页面信息
  378. this.sendPageInfo();
  379. resolve();
  380. };
  381. });
  382. // 等待一帧以确保DOM更新
  383. await new Promise((resolve) => requestAnimationFrame(resolve));
  384. // 触发动画
  385. document.body.classList.add("sidebar-open");
  386. iframe.classList.add("show");
  387. // 等待动画完成
  388. await new Promise((resolve) => {
  389. iframe.addEventListener("transitionend", resolve, { once: true });
  390. });
  391. this.isOpen = true;
  392. await Utils.setStorageData(SidebarManager.CONFIG.STORAGE_KEY, true);
  393. } catch (error) {
  394. console.error("Failed to create sidebar:", error);
  395. this.unwrapPageContent();
  396. }
  397. }
  398. /**
  399. * 移除侧边栏
  400. */
  401. async removeSidebar() {
  402. if (!this.isOpen) return;
  403. try {
  404. const sidebar = document.getElementById(this.sidebarId);
  405. if (sidebar) {
  406. document.body.classList.remove("sidebar-open");
  407. sidebar.classList.remove("show");
  408. // 等待动画完成后再移除元素
  409. await new Promise((resolve) => {
  410. sidebar.addEventListener(
  411. "transitionend",
  412. () => {
  413. this.unwrapPageContent();
  414. sidebar.remove();
  415. resolve();
  416. },
  417. { once: true }
  418. );
  419. });
  420. }
  421. this.isOpen = false;
  422. await Utils.setStorageData(SidebarManager.CONFIG.STORAGE_KEY, false);
  423. } catch (error) {
  424. console.error("Failed to remove sidebar:", error);
  425. }
  426. }
  427. /**
  428. * 切换侧边栏显示状态
  429. */
  430. toggle() {
  431. if (this.isOpen) {
  432. this.removeSidebar();
  433. } else {
  434. this.createSidebar();
  435. }
  436. }
  437. }
  438. // 初始化侧边栏管理器
  439. const sidebarManager = new SidebarManager();
  440. // 监听来自背景脚本的消息
  441. chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  442. if (message.action === "toggleSidebar") {
  443. sidebarManager.toggle();
  444. sendResponse({ success: true });
  445. }
  446. sendResponse({ success: true });
  447. });
  448. window.onload = () => {
  449. inputs = [...document.querySelectorAll('input')]
  450. }
  451. let inputs = []
  452. // 创建一个新的js文件用于处理侧边栏内部的关闭按钮事件
  453. const simulateCompleteUserAction = async (clickElement, inputElement, inputText, tdTitle) => {
  454. // 1. 模拟鼠标弹起事件
  455. const simulateMouseUp = (element) => {
  456. const mouseUpEvent = new MouseEvent('mouseup', {
  457. bubbles: true,
  458. cancelable: true,
  459. view: window,
  460. button: 0,
  461. buttons: 0,
  462. clientX: 0,
  463. clientY: 0,
  464. detail: 1
  465. });
  466. element.dispatchEvent(mouseUpEvent);
  467. };
  468. // 2. 模拟键盘输入
  469. const simulateTyping = async (element, text, delay = 50) => {
  470. element.focus();
  471. for (let char of text) {
  472. await new Promise(resolve => setTimeout(resolve, delay));
  473. // 按键按下
  474. const keydownEvent = new KeyboardEvent('keydown', {
  475. key: char,
  476. code: `Key${char.toUpperCase()}`,
  477. bubbles: true,
  478. cancelable: true
  479. });
  480. element.dispatchEvent(keydownEvent);
  481. // 更新输入值
  482. element.value += char;
  483. // 触发输入事件
  484. const inputEvent = new InputEvent('input', {
  485. bubbles: true,
  486. cancelable: true,
  487. data: char,
  488. inputType: 'insertText'
  489. });
  490. element.dispatchEvent(inputEvent);
  491. // 按键弹起
  492. const keyupEvent = new KeyboardEvent('keyup', {
  493. key: char,
  494. code: `Key${char.toUpperCase()}`,
  495. bubbles: true,
  496. cancelable: true
  497. });
  498. element.dispatchEvent(keyupEvent);
  499. }
  500. // 触发change事件
  501. element.dispatchEvent(new Event('change', { bubbles: true }));
  502. };
  503. // 3. 查找td元素
  504. const findTdByTitle = (title, timeout = 5000) => {
  505. return new Promise((resolve, reject) => {
  506. const startTime = Date.now();
  507. const find = () => {
  508. const td = document.querySelector(`td[title="${title}"]`);
  509. if (td) {
  510. resolve(td);
  511. return;
  512. }
  513. if (Date.now() - startTime > timeout) {
  514. reject(new Error(`未找到title为"${title}"的td元素`));
  515. return;
  516. }
  517. requestAnimationFrame(find);
  518. };
  519. find();
  520. });
  521. };
  522. // 4. 模拟点击事件
  523. const simulateClick = (element) => {
  524. const clickEvent = new MouseEvent('click', {
  525. bubbles: true,
  526. cancelable: true,
  527. view: window,
  528. detail: 1
  529. });
  530. element.dispatchEvent(clickEvent);
  531. };
  532. try {
  533. // 执行操作序列
  534. // 1. 触发鼠标弹起
  535. simulateMouseUp(clickElement);
  536. await new Promise(resolve => setTimeout(resolve, 100));
  537. // 2. 模拟键盘输入
  538. await simulateTyping(inputElement, inputText);
  539. await new Promise(resolve => setTimeout(resolve, 200));
  540. // 3. 查找并点击td元素
  541. const tdElement = await findTdByTitle(tdTitle);
  542. setTimeout(() => {
  543. tdElement.click()
  544. }, 100)
  545. return true;
  546. } catch (error) {
  547. throw error;
  548. }
  549. };