content.js 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  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.init();
  18. }
  19. /**
  20. * 初始化侧边栏
  21. */
  22. async init() {
  23. try {
  24. await this.checkAndRestoreState();
  25. this.setupEventListeners();
  26. } catch (error) {
  27. console.error("Sidebar initialization failed:", error);
  28. }
  29. }
  30. /**
  31. * 设置事件监听器
  32. */
  33. setupEventListeners() {
  34. // 监听页面加载完成事件
  35. window.addEventListener("load", () => this.checkAndRestoreState());
  36. // 监听来自 sidebar 的消息
  37. window.addEventListener("message", this.handleMessage.bind(this));
  38. // 监听窗口大小变化
  39. window.addEventListener(
  40. "resize",
  41. Utils.debounce(() => this.handleResize(), 100)
  42. );
  43. // 监听页面可见性变化
  44. document.addEventListener("visibilitychange", () => {
  45. if (!document.hidden) {
  46. this.checkAndRestoreState();
  47. }
  48. });
  49. // 监听 history 变化
  50. window.addEventListener("popstate", () => {
  51. this.checkAndRestoreState();
  52. });
  53. // 监听页面 URL 变化
  54. let lastUrl = location.href;
  55. new MutationObserver(() => {
  56. const url = location.href;
  57. if (url !== lastUrl) {
  58. lastUrl = url;
  59. this.checkAndRestoreState();
  60. }
  61. }).observe(document, { subtree: true, childList: true });
  62. // 监听来自sidebar的消息
  63. window.addEventListener("message", async (event) => {
  64. if (event.data.type === "COPY_TO_CLIPBOARD") {
  65. try {
  66. await navigator.clipboard.writeText(event.data.text);
  67. // 可选:发送成功消息回sidebar
  68. event.source.postMessage(
  69. {
  70. type: "COPY_SUCCESS",
  71. },
  72. "*"
  73. );
  74. } catch (err) {
  75. console.error("Failed to copy text:", err);
  76. // 可选:发送失败消息回sidebar
  77. event.source.postMessage(
  78. {
  79. type: "COPY_ERROR",
  80. error: err.message,
  81. },
  82. "*"
  83. );
  84. }
  85. }
  86. });
  87. // 监听来自iframe的消息
  88. window.addEventListener("message", (event) => {
  89. // 确保消息来自我们的iframe
  90. if (
  91. event.source ===
  92. document.getElementById("paiwise-sidebar")?.contentWindow
  93. ) {
  94. if (event.data.type === "ANALYZE_PAGE") {
  95. // 分析页面并返回结果
  96. const pageInfo = window.pageAnalyzer.analyzePage();
  97. // 发送分析结果回iframe
  98. event.source.postMessage(
  99. {
  100. type: "PAGE_ANALYSIS_RESULT",
  101. pageInfo: pageInfo,
  102. },
  103. "*"
  104. );
  105. }
  106. }
  107. });
  108. }
  109. /**
  110. * 处理接收到的消息
  111. * @param {MessageEvent} event
  112. */
  113. handleMessage(event) {
  114. if (event.data.action === "closeSidebar") {
  115. this.removeSidebar();
  116. }
  117. }
  118. /**
  119. * 处理窗口大小变化
  120. */
  121. handleResize() {
  122. const sidebar = document.getElementById(this.sidebarId);
  123. if (sidebar && this.isOpen) {
  124. sidebar.style.height = `${window.innerHeight}px`;
  125. }
  126. }
  127. /**
  128. * 检查并恢复侧边栏状态
  129. */
  130. async checkAndRestoreState() {
  131. try {
  132. const isOpen = await Utils.getStorageData(
  133. SidebarManager.CONFIG.STORAGE_KEY
  134. );
  135. if (isOpen && !this.isOpen) {
  136. // 只有当应该打开且当前未打开时才创建
  137. this.createSidebar();
  138. } else if (!isOpen && this.isOpen) {
  139. // 只有当应该关闭且当前打开时才移除
  140. this.removeSidebar();
  141. }
  142. } catch (error) {
  143. console.error("Failed to restore sidebar state:", error);
  144. }
  145. }
  146. /**
  147. * 包装页面内容
  148. */
  149. wrapPageContent() {
  150. if (document.getElementById(this.wrapperId)) return;
  151. const wrapper = document.createElement("div");
  152. wrapper.id = this.wrapperId;
  153. // 保存body的原始样式
  154. this.originalBodyStyle = {
  155. width: document.body.style.width,
  156. margin: document.body.style.margin,
  157. position: document.body.style.position,
  158. overflow: document.body.style.overflow,
  159. };
  160. // 包装内容
  161. while (document.body.firstChild) {
  162. if (document.body.firstChild.id !== this.sidebarId) {
  163. wrapper.appendChild(document.body.firstChild);
  164. } else {
  165. document.body.removeChild(document.body.firstChild);
  166. }
  167. }
  168. document.body.appendChild(wrapper);
  169. }
  170. /**
  171. * 解除页面内容包装
  172. */
  173. unwrapPageContent() {
  174. const wrapper = document.getElementById(this.wrapperId);
  175. if (!wrapper) return;
  176. // 恢复body的原始样式
  177. if (this.originalBodyStyle) {
  178. Object.assign(document.body.style, this.originalBodyStyle);
  179. }
  180. while (wrapper.firstChild) {
  181. document.body.insertBefore(wrapper.firstChild, wrapper);
  182. }
  183. wrapper.remove();
  184. }
  185. /**
  186. * 发送页面信息到iframe
  187. */
  188. sendPageInfo() {
  189. const iframe = document.getElementById(this.sidebarId);
  190. if (!iframe) return;
  191. // 获取页面favicon
  192. let favicon = "";
  193. const iconLink = document.querySelector('link[rel*="icon"]');
  194. if (iconLink) {
  195. favicon = iconLink.href;
  196. } else {
  197. // 如果没有找到,使用网站根目录的favicon.ico
  198. const url = new URL(window.location.href);
  199. favicon = `${url.protocol}//${url.hostname}/favicon.ico`;
  200. }
  201. // 发送页面信息到iframe
  202. iframe.contentWindow.postMessage(
  203. {
  204. type: "PAGE_INFO",
  205. pageInfo: {
  206. favicon: favicon,
  207. title: document.title,
  208. url: window.location.href,
  209. },
  210. },
  211. "*"
  212. );
  213. }
  214. /**
  215. * 创建侧边栏
  216. */
  217. async createSidebar() {
  218. if (document.getElementById(this.sidebarId)) return;
  219. try {
  220. this.wrapPageContent();
  221. const iframe = document.createElement("iframe");
  222. iframe.id = this.sidebarId;
  223. iframe.src = chrome.runtime.getURL("sidebar.html");
  224. // 先添加到DOM,但不添加show类
  225. document.body.appendChild(iframe);
  226. // 等待iframe加载完成
  227. await new Promise((resolve) => {
  228. iframe.onload = () => {
  229. // 发送页面信息
  230. this.sendPageInfo();
  231. resolve();
  232. };
  233. });
  234. // 等待一帧以确保DOM更新
  235. await new Promise((resolve) => requestAnimationFrame(resolve));
  236. // 触发动画
  237. document.body.classList.add("sidebar-open");
  238. iframe.classList.add("show");
  239. // 等待动画完成
  240. await new Promise((resolve) => {
  241. iframe.addEventListener("transitionend", resolve, { once: true });
  242. });
  243. this.isOpen = true;
  244. await Utils.setStorageData(SidebarManager.CONFIG.STORAGE_KEY, true);
  245. } catch (error) {
  246. console.error("Failed to create sidebar:", error);
  247. this.unwrapPageContent();
  248. }
  249. }
  250. /**
  251. * 移除侧边栏
  252. */
  253. async removeSidebar() {
  254. if (!this.isOpen) return;
  255. try {
  256. const sidebar = document.getElementById(this.sidebarId);
  257. if (sidebar) {
  258. document.body.classList.remove("sidebar-open");
  259. sidebar.classList.remove("show");
  260. // 等待动画完成后再移除元素
  261. await new Promise((resolve) => {
  262. sidebar.addEventListener(
  263. "transitionend",
  264. () => {
  265. this.unwrapPageContent();
  266. sidebar.remove();
  267. resolve();
  268. },
  269. { once: true }
  270. );
  271. });
  272. }
  273. this.isOpen = false;
  274. await Utils.setStorageData(SidebarManager.CONFIG.STORAGE_KEY, false);
  275. } catch (error) {
  276. console.error("Failed to remove sidebar:", error);
  277. }
  278. }
  279. /**
  280. * 切换侧边栏显示状态
  281. */
  282. toggle() {
  283. if (this.isOpen) {
  284. this.removeSidebar();
  285. } else {
  286. this.createSidebar();
  287. }
  288. }
  289. }
  290. // 初始化侧边栏管理器
  291. const sidebarManager = new SidebarManager();
  292. // 监听来自背景脚本的消息
  293. chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  294. if (message.action === "toggleSidebar") {
  295. sidebarManager.toggle();
  296. sendResponse({ success: true });
  297. }
  298. });
  299. // 创建一个新的js文件用于处理侧边栏内部的关闭按钮事件