content.js 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  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. // 监听页面 URL 变化
  71. new MutationObserver(() => {
  72. const url = location.href;
  73. if (url !== this.currentUrl) {
  74. this.currentUrl = url;
  75. this.updatePageInfo();
  76. this.checkAndRestoreState();
  77. }
  78. }).observe(document, { subtree: true, childList: true });
  79. // 监听来自sidebar的消息
  80. window.addEventListener("message", async (event) => {
  81. if (event.data.type === "COPY_TO_CLIPBOARD") {
  82. try {
  83. await navigator.clipboard.writeText(event.data.text);
  84. // 可选:发送成功消息回sidebar
  85. event.source.postMessage(
  86. {
  87. type: "COPY_SUCCESS",
  88. },
  89. "*"
  90. );
  91. } catch (err) {
  92. console.error("Failed to copy text:", err);
  93. // 可选:发送失败消息回sidebar
  94. event.source.postMessage(
  95. {
  96. type: "COPY_ERROR",
  97. error: err.message,
  98. },
  99. "*"
  100. );
  101. }
  102. }
  103. if (event.data.type === "FILL_INPUT") {
  104. inputs.find(input => input.placeholder.includes('账号')).value = event.data.data[1][0]
  105. inputs.find(input => input.placeholder.includes('密码')).value = event.data.data[1][1]
  106. }
  107. });
  108. // 监听来自iframe的消息
  109. window.addEventListener("message", (event) => {
  110. // 确保消息来自我们的iframe
  111. if (
  112. event.source ===
  113. document.getElementById("paiwise-sidebar")?.contentWindow
  114. ) {
  115. if (event.data.type === "FILL_INPUT") {
  116. event.source.postMessage(
  117. {
  118. type: "GE_T",
  119. pageInfo: pageInfo,
  120. },
  121. "*"
  122. );
  123. }
  124. if (event.data.type === "ANALYZE_PAGE") {
  125. // 分析页面并返回结果
  126. const pageInfo = window.pageAnalyzer.analyzePage();
  127. // 发送分析结果回iframe
  128. event.source.postMessage(
  129. {
  130. type: "PAGE_ANALYSIS_RESULT",
  131. pageInfo: pageInfo,
  132. },
  133. "*"
  134. );
  135. }
  136. }
  137. });
  138. }
  139. /**
  140. * 处理接收到的消息
  141. * @param {MessageEvent} event
  142. */
  143. handleMessage(event) {
  144. if (event.data.action === "closeSidebar") {
  145. this.removeSidebar();
  146. }
  147. }
  148. /**
  149. * 处理窗口大小变化
  150. */
  151. handleResize() {
  152. const sidebar = document.getElementById(this.sidebarId);
  153. if (sidebar && this.isOpen) {
  154. sidebar.style.height = `${window.innerHeight}px`;
  155. }
  156. }
  157. /**
  158. * 检查并恢复侧边栏状态
  159. */
  160. async checkAndRestoreState() {
  161. try {
  162. const isOpen = await Utils.getStorageData(
  163. SidebarManager.CONFIG.STORAGE_KEY
  164. );
  165. if (isOpen && !this.isOpen) {
  166. // 只有当应该打开且当前未打开时才创建
  167. this.createSidebar();
  168. } else if (!isOpen && this.isOpen) {
  169. // 只有当应该关闭且当前打开时才移除
  170. this.removeSidebar();
  171. }
  172. } catch (error) {
  173. console.error("Failed to restore sidebar state:", error);
  174. }
  175. }
  176. /**
  177. * 包装页面内容
  178. */
  179. wrapPageContent() {
  180. if (document.getElementById(this.wrapperId)) return;
  181. const wrapper = document.createElement("div");
  182. wrapper.id = this.wrapperId;
  183. // 保存body的原始样式
  184. this.originalBodyStyle = {
  185. width: document.body.style.width,
  186. margin: document.body.style.margin,
  187. position: document.body.style.position,
  188. overflow: document.body.style.overflow,
  189. };
  190. // 包装内容
  191. while (document.body.firstChild) {
  192. if (document.body.firstChild.id !== this.sidebarId) {
  193. wrapper.appendChild(document.body.firstChild);
  194. } else {
  195. document.body.removeChild(document.body.firstChild);
  196. }
  197. }
  198. document.body.appendChild(wrapper);
  199. }
  200. /**
  201. * 解除页面内容包装
  202. */
  203. unwrapPageContent() {
  204. const wrapper = document.getElementById(this.wrapperId);
  205. if (!wrapper) return;
  206. // 恢复body的原始样式
  207. if (this.originalBodyStyle) {
  208. Object.assign(document.body.style, this.originalBodyStyle);
  209. }
  210. while (wrapper.firstChild) {
  211. document.body.insertBefore(wrapper.firstChild, wrapper);
  212. }
  213. wrapper.remove();
  214. }
  215. /**
  216. * 发送页面信息到iframe
  217. */
  218. sendPageInfo() {
  219. this.updatePageInfo();
  220. }
  221. /**
  222. * 更新页面信息
  223. */
  224. updatePageInfo() {
  225. const iframe = document.getElementById(this.sidebarId);
  226. if (!iframe) return;
  227. // 获取最新的favicon
  228. const favicon = this.getFavicon();
  229. // 发送更新后的页面信息
  230. iframe.contentWindow.postMessage(
  231. {
  232. type: "PAGE_INFO",
  233. pageInfo: {
  234. favicon,
  235. title: document.title,
  236. url: window.location.href,
  237. },
  238. },
  239. "*"
  240. );
  241. }
  242. /**
  243. * 获取最新的favicon
  244. */
  245. getFavicon() {
  246. // 尝试获取动态favicon
  247. const iconLinks = Array.from(
  248. document.querySelectorAll('link[rel*="icon"]')
  249. );
  250. const favicon = iconLinks
  251. .sort((a, b) => {
  252. // 优先使用大尺寸图标
  253. const sizeA = parseInt(a.sizes?.value) || 0;
  254. const sizeB = parseInt(b.sizes?.value) || 0;
  255. return sizeB - sizeA;
  256. })
  257. .map((link) => link.href)
  258. .find(Boolean);
  259. if (favicon) return favicon;
  260. // 如果没有找到,返回网站根目录的favicon.ico
  261. const url = new URL(window.location.href);
  262. return `${url.protocol}//${url.hostname}/favicon.ico`;
  263. }
  264. /**
  265. * 创建侧边栏
  266. */
  267. async createSidebar() {
  268. if (document.getElementById(this.sidebarId)) return;
  269. try {
  270. this.wrapPageContent();
  271. const iframe = document.createElement("iframe");
  272. iframe.id = this.sidebarId;
  273. iframe.src = chrome.runtime.getURL("sidebar.html");
  274. // 先添加到DOM,但不添加show类
  275. document.body.appendChild(iframe);
  276. // 等待iframe加载完成
  277. await new Promise((resolve) => {
  278. iframe.onload = () => {
  279. // 发送页面信息
  280. this.sendPageInfo();
  281. resolve();
  282. };
  283. });
  284. // 等待一帧以确保DOM更新
  285. await new Promise((resolve) => requestAnimationFrame(resolve));
  286. // 触发动画
  287. document.body.classList.add("sidebar-open");
  288. iframe.classList.add("show");
  289. // 等待动画完成
  290. await new Promise((resolve) => {
  291. iframe.addEventListener("transitionend", resolve, { once: true });
  292. });
  293. this.isOpen = true;
  294. await Utils.setStorageData(SidebarManager.CONFIG.STORAGE_KEY, true);
  295. } catch (error) {
  296. console.error("Failed to create sidebar:", error);
  297. this.unwrapPageContent();
  298. }
  299. }
  300. /**
  301. * 移除侧边栏
  302. */
  303. async removeSidebar() {
  304. if (!this.isOpen) return;
  305. try {
  306. const sidebar = document.getElementById(this.sidebarId);
  307. if (sidebar) {
  308. document.body.classList.remove("sidebar-open");
  309. sidebar.classList.remove("show");
  310. // 等待动画完成后再移除元素
  311. await new Promise((resolve) => {
  312. sidebar.addEventListener(
  313. "transitionend",
  314. () => {
  315. this.unwrapPageContent();
  316. sidebar.remove();
  317. resolve();
  318. },
  319. { once: true }
  320. );
  321. });
  322. }
  323. this.isOpen = false;
  324. await Utils.setStorageData(SidebarManager.CONFIG.STORAGE_KEY, false);
  325. } catch (error) {
  326. console.error("Failed to remove sidebar:", error);
  327. }
  328. }
  329. /**
  330. * 切换侧边栏显示状态
  331. */
  332. toggle() {
  333. if (this.isOpen) {
  334. this.removeSidebar();
  335. } else {
  336. this.createSidebar();
  337. }
  338. }
  339. }
  340. // 初始化侧边栏管理器
  341. const sidebarManager = new SidebarManager();
  342. // 监听来自背景脚本的消息
  343. chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  344. if (message.action === "toggleSidebar") {
  345. sidebarManager.toggle();
  346. sendResponse({ success: true });
  347. }
  348. sendResponse({ success: true });
  349. });
  350. window.onload = () => {
  351. inputs = [...document.querySelectorAll('input')]
  352. }
  353. let inputs = []
  354. // 创建一个新的js文件用于处理侧边栏内部的关闭按钮事件