FaceBook 贴文悬浮截图按钮

在贴文右上新增一个悬浮截图按钮,按下后可以对贴文进行截图保存,方便与其他人分享

当前为 2025-06-09 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Floating Screenshot Button for Facebook Posts
  3. // @name:zh-TW FaceBook 貼文懸浮截圖按鈕
  4. // @name:zh-CN FaceBook 贴文悬浮截图按钮
  5. // @namespace http://tampermonkey.net/
  6. // @version 1.8
  7. // @description A floating screenshot button is added to the top-right corner of the post. When clicked, it allows users to capture and save a screenshot of the post, making it easier to share with others.
  8. // @description:zh-TW 在貼文右上新增一個懸浮截圖按鈕,按下後可以對貼文進行截圖保存,方便與其他人分享
  9. // @description:zh-CN 在贴文右上新增一个悬浮截图按钮,按下后可以对贴文进行截图保存,方便与其他人分享
  10. // @author chatgpt
  11. // @match https://www.facebook.com/*
  12. // @grant none
  13. // @require https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js
  14. // @license MIT
  15. // ==/UserScript==
  16.  
  17. (function() {
  18. 'use strict';
  19.  
  20. let lastRun = 0; // 上次執行時間,用於防抖動
  21. const debounceDelay = 1000; // 防抖動延遲,避免過度頻繁執行
  22.  
  23. // 從貼文元素中取得 FB 貼文 ID
  24. function getFbidFromPost(post) {
  25. // 嘗試從貼文內含 fbid 或 story_fbid 的連結抓取
  26. const links = Array.from(post.querySelectorAll('a[href*="fbid="], a[href*="story_fbid="]'));
  27. for (const a of links) {
  28. try {
  29. const url = new URL(a.href);
  30. const fbid = url.searchParams.get('fbid') || url.searchParams.get('story_fbid'); // 從網址參數取得 ID
  31. if (fbid) return fbid;
  32. } catch(e) {}
  33. }
  34.  
  35. // 嘗試從 data-ft 屬性字串中用正則抓 top_level_post_id
  36. try {
  37. const dataFt = post.getAttribute('data-ft');
  38. if (dataFt) {
  39. const match = dataFt.match(/"top_level_post_id":"(\d+)"/);
  40. if (match) return match[1];
  41. }
  42. } catch(e) {}
  43.  
  44. // 嘗試從當前頁面網址抓 fbid 或 story_fbid 參數
  45. try {
  46. const url = new URL(window.location.href);
  47. const fbid = url.searchParams.get('fbid') || url.searchParams.get('story_fbid');
  48. if (fbid) return fbid;
  49. } catch(e) {}
  50.  
  51. return 'unknownFBID'; // 都抓不到時回傳預設字串
  52. }
  53.  
  54. // 監聽頁面 DOM 變動,動態新增截圖按鈕
  55. const observer = new MutationObserver(() => {
  56. const now = Date.now();
  57. if (now - lastRun < debounceDelay) return; // 防抖,避免頻繁觸發
  58. lastRun = now;
  59.  
  60. // 找所有貼文容器元素
  61. document.querySelectorAll('div.x1lliihq').forEach(post => {
  62. if (post.dataset.sbtn === '1') return; // 已加入按鈕就跳過
  63.  
  64. // 找貼文中的按鈕群組容器
  65. let btnGroup = post.querySelector('div[role="group"]')
  66. || post.querySelector('div.xqcrz7y')
  67. || post.querySelector('div.x1qx5ct2');
  68. if (!btnGroup) return; // 找不到按鈕群組就跳過
  69.  
  70. post.dataset.sbtn = '1'; // 標記已加按鈕
  71. btnGroup.style.position = 'relative'; // 設相對定位,方便絕對定位按鈕
  72.  
  73. // 建立截圖按鈕
  74. const btn = document.createElement('div');
  75. btn.textContent = '📸'; // 按鈕文字(相機圖示)
  76. btn.title = '截圖貼文'; // 提示文字
  77. Object.assign(btn.style, { // 設定按鈕樣式
  78. position: 'absolute',
  79. left: '-40px',
  80. top: '0',
  81. width: '32px',
  82. height: '32px',
  83. display: 'flex',
  84. alignItems: 'center',
  85. justifyContent: 'center',
  86. borderRadius: '50%',
  87. backgroundColor: '#3A3B3C',
  88. color: 'white',
  89. cursor: 'pointer',
  90. zIndex: '9999',
  91. transition: 'background .2s'
  92. });
  93. // 滑鼠移入變色
  94. btn.addEventListener('mouseenter', () => btn.style.backgroundColor = '#4E4F50');
  95. // 滑鼠移出還原顏色
  96. btn.addEventListener('mouseleave', () => btn.style.backgroundColor = '#3A3B3C');
  97.  
  98. // 按鈕點擊事件,進行截圖
  99. btn.addEventListener('click', async e => {
  100. e.stopPropagation(); // 防止事件冒泡
  101. btn.textContent = '⏳'; // 顯示等待中圖示
  102. btn.style.pointerEvents = 'none'; // 禁用按鈕避免重複點擊
  103.  
  104. try {
  105. if (!window.html2canvas) throw new Error('html2canvas 尚未載入');
  106.  
  107. post.scrollIntoView({ behavior: 'smooth', block: 'center' }); // 滾動貼文至畫面中央
  108. await new Promise(r => setTimeout(r, 500)); // 等待 0.5 秒讓畫面穩定
  109.  
  110. const fbid = getFbidFromPost(post); // 取得貼文 ID
  111.  
  112. // 產生時間字串,用於檔名
  113. const nowDate = new Date();
  114. const pad = n => n.toString().padStart(2, '0');
  115. const datetimeStr =
  116. nowDate.getFullYear().toString() +
  117. pad(nowDate.getMonth() + 1) +
  118. pad(nowDate.getDate()) + '_' +
  119. pad(nowDate.getHours()) + '_' +
  120. pad(nowDate.getMinutes()) + '_' +
  121. pad(nowDate.getSeconds());
  122.  
  123. // 使用 html2canvas 將貼文轉成 canvas
  124. const canvas = await html2canvas(post, {
  125. useCORS: true,
  126. allowTaint: true,
  127. backgroundColor: 'null', //背景色設定,null 透明,white 白,black 黑
  128. scale: 2, //畫質設定,建議使用2,或者window.devicePixelRatio
  129. logging: false,
  130. foreignObjectRendering: false
  131. });
  132.  
  133. const filename = `${fbid}_${datetimeStr}.png`; // 檔名格式:FBID_時間.png
  134.  
  135. // 建立下載連結並觸發下載
  136. const link = document.createElement('a');
  137. link.href = canvas.toDataURL('image/png');
  138. link.download = filename;
  139. link.click();
  140.  
  141. btn.textContent = '✅'; // 成功顯示勾勾
  142. } catch (err) {
  143. console.error('截圖錯誤:', err); // 錯誤輸出到 console
  144. alert('截圖失敗,請稍後再試'); // 跳出錯誤提示
  145. btn.textContent = '❌'; // 顯示錯誤圖示
  146. }
  147.  
  148. // 1秒後還原按鈕狀態
  149. setTimeout(() => {
  150. btn.textContent = '📸';
  151. btn.style.pointerEvents = 'auto';
  152. }, 1000);
  153. });
  154.  
  155. btnGroup.appendChild(btn); // 將按鈕加入按鈕群組
  156. });
  157. });
  158.  
  159. // 監聽整個 body 的 DOM 變化
  160. observer.observe(document.body, { childList: true, subtree: true });
  161.  
  162. })();