content.js 9.3 KB

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