萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

純 JavaScript 實現 IE 右鍵選單擴充:選取文字一鍵分享至新浪微博

核心原理

IE 允許透過註冊表 HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\MenuExt 新增右鍵選單項目,指向一個 HTML/JS 檔案。該檔案透過 window.external.menuArguments 取得來源視窗的 document、selection 等物件,實現「選取文字 → 組合分享 URL → 開啟微博分享頁」流程。

註冊表結構(.reg 檔)

Windows Registry Editor Version 5.00

[HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\MenuExt\&分享到微博]
@="file://C:\\Path\\To\\share_weibo.htm"
"Contexts"=dword:00000023
  • Contexts = 0x23 (1|2|16|32):預設(1) + 連結(2) + 圖片(16) + 文字選取(32) = 35 (0x23)。
  • 預設值 @ 指向處理頁面絕對路徑(需 file:// 協定)。

處理頁面 share_weibo.htm

<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>分享到微博</title></head><body>
<script>
(function() {
  var ext = window.external.menuArguments;
  var doc = ext.document;
  var sel = doc.selection;
  var range = sel ? sel.createRange() : null;
  var text = (range && range.text) ? range.text : '';
  // 無選取文字時 fallback 為頁面標題
  if (!text) text = doc.title;

  if (text) {
    var url = 'https://service.weibo.com/share/share.php'
      + '?title=' + encodeURIComponent(text)
      + '&url=' + encodeURIComponent(doc.URL)
      + '&source=' + encodeURIComponent('我的工具')
      + '&appkey=1027675428'; // 需申請專屬 AppKey
    window.open(url, '_blank', 'width=600,height=400,top='+(screen.height-400)/2+',left='+(screen.width-600)/2);
  }
})();
</script>
</body></html>

批次安裝腳本 (install.bat)

@echo off
reg import "%~dp0share_weibo.reg"
echo 安裝完成,請重新啟動 IE。
pause

限制與現代替代

  • 僅限 IE:Chrome/Edge/Firefox 需開發 WebExtension(Manifest V3)。
  • 僅能取得純文字:selection.createRange().text 無法取得 HTML/圖片/連結結構。
  • 安全性:現代 Windows 對 MenuExt 寫入有 UAC 限制,需管理員權限。
  • 替代方案:書籤小工具 — 將 JS 封裝為 javascript:(function(){...})() 存為書籤,跨瀏覽器通用。
copyright © 萬盛學電腦網 all rights reserved