content.js 17 KB

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