content.js 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  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. }
  88. /**
  89. * 处理接收到的消息
  90. * @param {MessageEvent} event
  91. */
  92. handleMessage(event) {
  93. if (event.data.action === "closeSidebar") {
  94. this.removeSidebar();
  95. }
  96. }
  97. /**
  98. * 处理窗口大小变化
  99. */
  100. handleResize() {
  101. const sidebar = document.getElementById(this.sidebarId);
  102. if (sidebar && this.isOpen) {
  103. sidebar.style.height = `${window.innerHeight}px`;
  104. }
  105. }
  106. /**
  107. * 检查并恢复侧边栏状态
  108. */
  109. async checkAndRestoreState() {
  110. try {
  111. const isOpen = await Utils.getStorageData(
  112. SidebarManager.CONFIG.STORAGE_KEY
  113. );
  114. if (isOpen && !this.isOpen) {
  115. // 只有当应该打开且当前未打开时才创建
  116. this.createSidebar();
  117. } else if (!isOpen && this.isOpen) {
  118. // 只有当应该关闭且当前打开时才移除
  119. this.removeSidebar();
  120. }
  121. } catch (error) {
  122. console.error("Failed to restore sidebar state:", error);
  123. }
  124. }
  125. /**
  126. * 包装页面内容
  127. */
  128. wrapPageContent() {
  129. if (document.getElementById(this.wrapperId)) return;
  130. const wrapper = document.createElement("div");
  131. wrapper.id = this.wrapperId;
  132. // 保存body的原始样式
  133. this.originalBodyStyle = {
  134. width: document.body.style.width,
  135. margin: document.body.style.margin,
  136. position: document.body.style.position,
  137. overflow: document.body.style.overflow,
  138. };
  139. // 包装内容
  140. while (document.body.firstChild) {
  141. if (document.body.firstChild.id !== this.sidebarId) {
  142. wrapper.appendChild(document.body.firstChild);
  143. } else {
  144. document.body.removeChild(document.body.firstChild);
  145. }
  146. }
  147. document.body.appendChild(wrapper);
  148. }
  149. /**
  150. * 解除页面内容包装
  151. */
  152. unwrapPageContent() {
  153. const wrapper = document.getElementById(this.wrapperId);
  154. if (!wrapper) return;
  155. // 恢复body的原始样式
  156. if (this.originalBodyStyle) {
  157. Object.assign(document.body.style, this.originalBodyStyle);
  158. }
  159. while (wrapper.firstChild) {
  160. document.body.insertBefore(wrapper.firstChild, wrapper);
  161. }
  162. wrapper.remove();
  163. }
  164. /**
  165. * 创建侧边栏
  166. */
  167. async createSidebar() {
  168. if (document.getElementById(this.sidebarId)) return;
  169. try {
  170. this.wrapPageContent();
  171. const iframe = document.createElement("iframe");
  172. iframe.id = this.sidebarId;
  173. iframe.src = chrome.runtime.getURL("sidebar.html");
  174. document.body.appendChild(iframe);
  175. // 使用 RAF 确保 DOM 更新后再添加动画类
  176. requestAnimationFrame(() => {
  177. document.body.classList.add("sidebar-open");
  178. iframe.classList.add("show");
  179. });
  180. this.isOpen = true;
  181. await Utils.setStorageData(SidebarManager.CONFIG.STORAGE_KEY, true);
  182. } catch (error) {
  183. console.error("Failed to create sidebar:", error);
  184. this.unwrapPageContent();
  185. }
  186. }
  187. /**
  188. * 移除侧边栏
  189. */
  190. async removeSidebar() {
  191. if (!this.isOpen) return;
  192. try {
  193. const sidebar = document.getElementById(this.sidebarId);
  194. if (sidebar) {
  195. document.body.classList.remove("sidebar-open");
  196. sidebar.classList.remove("show");
  197. // 等待动画完成后再移除元素
  198. await new Promise((resolve) => {
  199. sidebar.addEventListener(
  200. "transitionend",
  201. () => {
  202. this.unwrapPageContent();
  203. sidebar.remove();
  204. resolve();
  205. },
  206. { once: true }
  207. );
  208. });
  209. }
  210. this.isOpen = false;
  211. await Utils.setStorageData(SidebarManager.CONFIG.STORAGE_KEY, false);
  212. } catch (error) {
  213. console.error("Failed to remove sidebar:", error);
  214. }
  215. }
  216. /**
  217. * 切换侧边栏显示状态
  218. */
  219. toggle() {
  220. if (this.isOpen) {
  221. this.removeSidebar();
  222. } else {
  223. this.createSidebar();
  224. }
  225. }
  226. }
  227. // 初始化侧边栏管理器
  228. const sidebarManager = new SidebarManager();
  229. // 监听来自背景脚本的消息
  230. chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  231. if (message.action === "toggleSidebar") {
  232. sidebarManager.toggle();
  233. sendResponse({ success: true });
  234. }
  235. });
  236. // 创建一个新的js文件用于处理侧边栏内部的关闭按钮事件