content.js 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  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. * 发送页面信息到iframe
  166. */
  167. sendPageInfo() {
  168. const iframe = document.getElementById(this.sidebarId);
  169. if (!iframe) return;
  170. // 获取页面favicon
  171. let favicon = "";
  172. const iconLink = document.querySelector('link[rel*="icon"]');
  173. if (iconLink) {
  174. favicon = iconLink.href;
  175. } else {
  176. // 如果没有找到,使用网站根目录的favicon.ico
  177. const url = new URL(window.location.href);
  178. favicon = `${url.protocol}//${url.hostname}/favicon.ico`;
  179. }
  180. // 发送页面信息到iframe
  181. iframe.contentWindow.postMessage(
  182. {
  183. type: "PAGE_INFO",
  184. pageInfo: {
  185. favicon: favicon,
  186. title: document.title,
  187. url: window.location.href,
  188. },
  189. },
  190. "*"
  191. );
  192. }
  193. /**
  194. * 创建侧边栏
  195. */
  196. async createSidebar() {
  197. if (document.getElementById(this.sidebarId)) return;
  198. try {
  199. this.wrapPageContent();
  200. const iframe = document.createElement("iframe");
  201. iframe.id = this.sidebarId;
  202. iframe.src = chrome.runtime.getURL("sidebar.html");
  203. document.body.appendChild(iframe);
  204. // 使用 RAF 确保 DOM 更新后再添加动画类
  205. requestAnimationFrame(() => {
  206. document.body.classList.add("sidebar-open");
  207. iframe.classList.add("show");
  208. });
  209. this.isOpen = true;
  210. await Utils.setStorageData(SidebarManager.CONFIG.STORAGE_KEY, true);
  211. // 在iframe加载完成后发送页面信息
  212. iframe.onload = () => {
  213. this.sendPageInfo();
  214. };
  215. } catch (error) {
  216. console.error("Failed to create sidebar:", error);
  217. this.unwrapPageContent();
  218. }
  219. }
  220. /**
  221. * 移除侧边栏
  222. */
  223. async removeSidebar() {
  224. if (!this.isOpen) return;
  225. try {
  226. const sidebar = document.getElementById(this.sidebarId);
  227. if (sidebar) {
  228. document.body.classList.remove("sidebar-open");
  229. sidebar.classList.remove("show");
  230. // 等待动画完成后再移除元素
  231. await new Promise((resolve) => {
  232. sidebar.addEventListener(
  233. "transitionend",
  234. () => {
  235. this.unwrapPageContent();
  236. sidebar.remove();
  237. resolve();
  238. },
  239. { once: true }
  240. );
  241. });
  242. }
  243. this.isOpen = false;
  244. await Utils.setStorageData(SidebarManager.CONFIG.STORAGE_KEY, false);
  245. } catch (error) {
  246. console.error("Failed to remove sidebar:", error);
  247. }
  248. }
  249. /**
  250. * 切换侧边栏显示状态
  251. */
  252. toggle() {
  253. if (this.isOpen) {
  254. this.removeSidebar();
  255. } else {
  256. this.createSidebar();
  257. }
  258. }
  259. }
  260. // 初始化侧边栏管理器
  261. const sidebarManager = new SidebarManager();
  262. // 监听来自背景脚本的消息
  263. chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  264. if (message.action === "toggleSidebar") {
  265. sidebarManager.toggle();
  266. sendResponse({ success: true });
  267. }
  268. });
  269. // 创建一个新的js文件用于处理侧边栏内部的关闭按钮事件