content.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  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. formatDate
  154. const input = formChildren.find(child => child.id === item.findByValue)
  155. if (excelDataA[item.excelColumn][index]) {
  156. await simulateCompleteUserAction(input, input, formatDate(excelDataA[item.excelColumn][index]), formatDate(excelDataA[item.excelColumn][index]))
  157. }
  158. }
  159. } else if (item.findBy === 'placeholder') {
  160. const input = formChildren.find(child => child.placeholder === item.findByValue)
  161. if (input) {
  162. simulateUserInput(input, excelDataA[item.excelColumn][index])
  163. }
  164. }
  165. }
  166. }
  167. let form = null
  168. let formChildren = []
  169. let excelDataA = []
  170. // 监听来自sidebar的消息
  171. window.addEventListener("message", async (event) => {
  172. if (event.data.type === "COPY_TO_CLIPBOARD") {
  173. try {
  174. await navigator.clipboard.writeText(event.data.text);
  175. // 可选:发送成功消息回sidebar
  176. event.source.postMessage(
  177. {
  178. type: "COPY_SUCCESS",
  179. },
  180. "*"
  181. );
  182. } catch (err) {
  183. console.error("Failed to copy text:", err);
  184. // 可选:发送失败消息回sidebar
  185. event.source.postMessage(
  186. {
  187. type: "COPY_ERROR",
  188. error: err.message,
  189. },
  190. "*"
  191. );
  192. }
  193. }
  194. if (event.data.type === "HANDLE_FILL_INPUT") {
  195. const { formData, excelData } = event.data.data
  196. excelDataA = excelData
  197. console.log(formChildren, excelDataA);
  198. await handleFillInput(formData, 0)
  199. }
  200. });
  201. // 监听来自iframe的消息
  202. window.addEventListener("message", (event) => {
  203. // 确保消息来自我们的iframe
  204. if (
  205. event.source ===
  206. document.getElementById("paiwise-sidebar")?.contentWindow
  207. ) {
  208. if (event.data.type === "FILL_INPUT") {
  209. event.source.postMessage(
  210. {
  211. type: "GE_T",
  212. pageInfo: pageInfo,
  213. },
  214. "*"
  215. );
  216. }
  217. if (event.data.type === "ANALYZE_PAGE") {
  218. form = document.querySelectorAll("form")[0];
  219. formChildren = [...form.elements]
  220. // 分析页面并返回结果
  221. const pageInfo = window.pageAnalyzer.analyzePage();
  222. // 发送分析结果回iframe
  223. event.source.postMessage(
  224. {
  225. type: "PAGE_ANALYSIS_RESULT",
  226. pageInfo: form.outerHTML,
  227. },
  228. "*"
  229. );
  230. }
  231. }
  232. });
  233. }
  234. handleUserName(input) {
  235. return input.placeholder.includes('账号') || input.placeholder.includes('用户名')
  236. }
  237. /**
  238. * 处理接收到的消息
  239. * @param {MessageEvent} event
  240. */
  241. handleMessage(event) {
  242. if (event.data.action === "closeSidebar") {
  243. this.removeSidebar();
  244. }
  245. }
  246. /**
  247. * 处理窗口大小变化
  248. */
  249. handleResize() {
  250. const sidebar = document.getElementById(this.sidebarId);
  251. if (sidebar && this.isOpen) {
  252. sidebar.style.height = `${window.innerHeight}px`;
  253. }
  254. }
  255. /**
  256. * 检查并恢复侧边栏状态
  257. */
  258. async checkAndRestoreState() {
  259. try {
  260. const isOpen = await Utils.getStorageData(
  261. SidebarManager.CONFIG.STORAGE_KEY
  262. );
  263. if (isOpen && !this.isOpen) {
  264. // 只有当应该打开且当前未打开时才创建
  265. this.createSidebar();
  266. } else if (!isOpen && this.isOpen) {
  267. // 只有当应该关闭且当前打开时才移除
  268. this.removeSidebar();
  269. }
  270. } catch (error) {
  271. console.error("Failed to restore sidebar state:", error);
  272. }
  273. }
  274. /**
  275. * 包装页面内容
  276. */
  277. wrapPageContent() {
  278. if (document.getElementById(this.wrapperId)) return;
  279. const wrapper = document.createElement("div");
  280. wrapper.id = this.wrapperId;
  281. // 保存body的原始样式
  282. this.originalBodyStyle = {
  283. width: document.body.style.width,
  284. margin: document.body.style.margin,
  285. position: document.body.style.position,
  286. overflow: document.body.style.overflow,
  287. };
  288. // 包装内容
  289. while (document.body.firstChild) {
  290. if (document.body.firstChild.id !== this.sidebarId) {
  291. wrapper.appendChild(document.body.firstChild);
  292. } else {
  293. document.body.removeChild(document.body.firstChild);
  294. }
  295. }
  296. document.body.appendChild(wrapper);
  297. }
  298. /**
  299. * 解除页面内容包装
  300. */
  301. unwrapPageContent() {
  302. const wrapper = document.getElementById(this.wrapperId);
  303. if (!wrapper) return;
  304. // 恢复body的原始样式
  305. if (this.originalBodyStyle) {
  306. Object.assign(document.body.style, this.originalBodyStyle);
  307. }
  308. while (wrapper.firstChild) {
  309. document.body.insertBefore(wrapper.firstChild, wrapper);
  310. }
  311. wrapper.remove();
  312. }
  313. /**
  314. * 发送页面信息到iframe
  315. */
  316. sendPageInfo() {
  317. this.updatePageInfo();
  318. }
  319. /**
  320. * 更新页面信息
  321. */
  322. updatePageInfo() {
  323. const iframe = document.getElementById(this.sidebarId);
  324. if (!iframe) return;
  325. // 获取最新的favicon
  326. const favicon = this.getFavicon();
  327. // 发送更新后的页面信息
  328. iframe.contentWindow.postMessage(
  329. {
  330. type: "PAGE_INFO",
  331. pageInfo: {
  332. favicon,
  333. title: document.title,
  334. url: window.location.href,
  335. iframe: window.pageAnalyzer.analyzePage()
  336. },
  337. },
  338. "*"
  339. );
  340. }
  341. /**
  342. * 获取最新的favicon
  343. */
  344. getFavicon() {
  345. // 尝试获取动态favicon
  346. const iconLinks = Array.from(
  347. document.querySelectorAll('link[rel*="icon"]')
  348. );
  349. const favicon = iconLinks
  350. .sort((a, b) => {
  351. // 优先使用大尺寸图标
  352. const sizeA = parseInt(a.sizes?.value) || 0;
  353. const sizeB = parseInt(b.sizes?.value) || 0;
  354. return sizeB - sizeA;
  355. })
  356. .map((link) => link.href)
  357. .find(Boolean);
  358. if (favicon) return favicon;
  359. // 如果没有找到,返回网站根目录的favicon.ico
  360. const url = new URL(window.location.href);
  361. return `${url.protocol}//${url.hostname}/favicon.ico`;
  362. }
  363. /**
  364. * 创建侧边栏
  365. */
  366. async createSidebar() {
  367. if (document.getElementById(this.sidebarId)) return;
  368. try {
  369. this.wrapPageContent();
  370. const iframe = document.createElement("iframe");
  371. iframe.id = this.sidebarId;
  372. iframe.src = chrome.runtime.getURL("sidebar.html");
  373. // 先添加到DOM,但不添加show类
  374. document.body.appendChild(iframe);
  375. // 等待iframe加载完成
  376. await new Promise((resolve) => {
  377. iframe.onload = () => {
  378. // 发送页面信息
  379. this.sendPageInfo();
  380. resolve();
  381. };
  382. });
  383. // 等待一帧以确保DOM更新
  384. await new Promise((resolve) => requestAnimationFrame(resolve));
  385. // 触发动画
  386. document.body.classList.add("sidebar-open");
  387. iframe.classList.add("show");
  388. // 等待动画完成
  389. await new Promise((resolve) => {
  390. iframe.addEventListener("transitionend", resolve, { once: true });
  391. });
  392. this.isOpen = true;
  393. await Utils.setStorageData(SidebarManager.CONFIG.STORAGE_KEY, true);
  394. } catch (error) {
  395. console.error("Failed to create sidebar:", error);
  396. this.unwrapPageContent();
  397. }
  398. }
  399. /**
  400. * 移除侧边栏
  401. */
  402. async removeSidebar() {
  403. if (!this.isOpen) return;
  404. try {
  405. const sidebar = document.getElementById(this.sidebarId);
  406. if (sidebar) {
  407. document.body.classList.remove("sidebar-open");
  408. sidebar.classList.remove("show");
  409. // 等待动画完成后再移除元素
  410. await new Promise((resolve) => {
  411. sidebar.addEventListener(
  412. "transitionend",
  413. () => {
  414. this.unwrapPageContent();
  415. sidebar.remove();
  416. resolve();
  417. },
  418. { once: true }
  419. );
  420. });
  421. }
  422. this.isOpen = false;
  423. await Utils.setStorageData(SidebarManager.CONFIG.STORAGE_KEY, false);
  424. } catch (error) {
  425. console.error("Failed to remove sidebar:", error);
  426. }
  427. }
  428. /**
  429. * 切换侧边栏显示状态
  430. */
  431. toggle() {
  432. if (this.isOpen) {
  433. this.removeSidebar();
  434. } else {
  435. this.createSidebar();
  436. }
  437. }
  438. }
  439. // 初始化侧边栏管理器
  440. const sidebarManager = new SidebarManager();
  441. // 监听来自背景脚本的消息
  442. chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  443. if (message.action === "toggleSidebar") {
  444. sidebarManager.toggle();
  445. sendResponse({ success: true });
  446. }
  447. sendResponse({ success: true });
  448. });
  449. window.onload = () => {
  450. inputs = [...document.querySelectorAll('input')]
  451. }
  452. let inputs = []
  453. // 创建一个新的js文件用于处理侧边栏内部的关闭按钮事件
  454. const simulateCompleteUserAction = async (clickElement, inputElement, inputText, tdTitle) => {
  455. // 1. 模拟鼠标弹起事件
  456. const simulateMouseUp = (element) => {
  457. const mouseUpEvent = new MouseEvent('mouseup', {
  458. bubbles: true,
  459. cancelable: true,
  460. view: window,
  461. button: 0,
  462. buttons: 0,
  463. clientX: 0,
  464. clientY: 0,
  465. detail: 1
  466. });
  467. element.dispatchEvent(mouseUpEvent);
  468. };
  469. // 2. 模拟键盘输入
  470. const simulateTyping = async (element, text, delay = 50) => {
  471. element.focus();
  472. for (let char of text) {
  473. await new Promise(resolve => setTimeout(resolve, delay));
  474. // 按键按下
  475. const keydownEvent = new KeyboardEvent('keydown', {
  476. key: char,
  477. code: `Key${char.toUpperCase()}`,
  478. bubbles: true,
  479. cancelable: true
  480. });
  481. element.dispatchEvent(keydownEvent);
  482. // 更新输入值
  483. element.value += char;
  484. // 触发输入事件
  485. const inputEvent = new InputEvent('input', {
  486. bubbles: true,
  487. cancelable: true,
  488. data: char,
  489. inputType: 'insertText'
  490. });
  491. element.dispatchEvent(inputEvent);
  492. // 按键弹起
  493. const keyupEvent = new KeyboardEvent('keyup', {
  494. key: char,
  495. code: `Key${char.toUpperCase()}`,
  496. bubbles: true,
  497. cancelable: true
  498. });
  499. element.dispatchEvent(keyupEvent);
  500. }
  501. // 触发change事件
  502. element.dispatchEvent(new Event('change', { bubbles: true }));
  503. };
  504. // 3. 查找td元素
  505. const findTdByTitle = (title, timeout = 5000) => {
  506. return new Promise((resolve, reject) => {
  507. const startTime = Date.now();
  508. const find = () => {
  509. const td = document.querySelector(`td[title="${title}"]`);
  510. if (td) {
  511. resolve(td);
  512. return;
  513. }
  514. if (Date.now() - startTime > timeout) {
  515. reject(new Error(`未找到title为"${title}"的td元素`));
  516. return;
  517. }
  518. requestAnimationFrame(find);
  519. };
  520. find();
  521. });
  522. };
  523. // 4. 模拟点击事件
  524. const simulateClick = (element) => {
  525. const clickEvent = new MouseEvent('click', {
  526. bubbles: true,
  527. cancelable: true,
  528. view: window,
  529. detail: 1
  530. });
  531. element.dispatchEvent(clickEvent);
  532. };
  533. try {
  534. // 执行操作序列
  535. // 1. 触发鼠标弹起
  536. simulateMouseUp(clickElement);
  537. await new Promise(resolve => setTimeout(resolve, 100));
  538. // 2. 模拟键盘输入
  539. await simulateTyping(inputElement, inputText);
  540. await new Promise(resolve => setTimeout(resolve, 200));
  541. // 3. 查找并点击td元素
  542. const tdElement = await findTdByTitle(tdTitle);
  543. setTimeout(() => {
  544. tdElement.click()
  545. }, 100)
  546. return true;
  547. } catch (error) {
  548. throw error;
  549. }
  550. };
  551. function formatDate(date) {
  552. const d = new Date(date);
  553. const year = d.getFullYear();
  554. const month = String(d.getMonth() + 1).padStart(2, '0'); // 月份从0开始,需要加1,并确保两位数
  555. const day = String(d.getDate()).padStart(2, '0'); // 确保两位数
  556. return `${year}-${month}-${day}`;
  557. }