是否可用Delphi开发Chrome扩展?类Google词典扩展实现咨询
好问题!Chrome扩展的核心技术栈是HTML、CSS和JavaScript,没法直接用Delphi写完整的扩展包,但我们可以通过Chrome Native Messaging机制,把Delphi程序作为扩展的“后端服务”,结合前端扩展代码来实现你想要的点击单词弹出翻译的功能。
核心实现逻辑
Chrome扩展负责和浏览器页面交互(监听点击、选中文本、显示弹窗),当需要翻译时,通过Native Messaging把选中的单词发送给Delphi程序;Delphi程序处理翻译逻辑(比如查询本地词库、调用翻译接口),再把结果返回给扩展,最后由扩展弹窗展示翻译内容。
分步实现 & 代码示例
1. 编写Chrome扩展前端部分
这部分是标准的扩展代码,负责页面交互:
manifest.json(扩展配置文件)
{ "manifest_version": 3, "name": "Delphi-Powered Dictionary", "version": "1.0", "permissions": ["nativeMessaging", "activeTab"], "content_scripts": [ { "matches": ["<all_urls>"], "js": ["content.js"] } ], "action": { "default_popup": "popup.html" } }
content.js(页面交互脚本)
负责监听鼠标点击,获取选中的单词,发送给Delphi宿主:
document.addEventListener('mouseup', function(e) { const selectedText = window.getSelection().toString().trim(); if (selectedText && selectedText.length < 50) { // 只处理短文本(单词) // 发送消息给Native Messaging宿主 chrome.runtime.sendNativeMessage('com.yourcompany.delphidictionary', {word: selectedText}, function(response) { if (response && response.translation) { // 创建弹窗显示翻译 showTranslationPopup(e.clientX, e.clientY, response.translation); } } ); } }); // 显示翻译弹窗的函数 function showTranslationPopup(x, y, translation) { // 先移除已存在的弹窗 const oldPopup = document.getElementById('dict-popup'); if (oldPopup) oldPopup.remove(); const popup = document.createElement('div'); popup.id = 'dict-popup'; popup.style.position = 'fixed'; popup.style.left = `${x + 10}px`; popup.style.top = `${y + 10}px`; popup.style.padding = '8px 12px'; popup.style.background = '#fff'; popup.style.border = '1px solid #ccc'; popup.style.borderRadius = '4px'; popup.style.boxShadow = '0 2px 4px rgba(0,0,0,0.2)'; popup.style.zIndex = '9999'; popup.textContent = translation; document.body.appendChild(popup); // 点击页面其他地方关闭弹窗 setTimeout(() => { document.addEventListener('click', function closePopup() { popup.remove(); document.removeEventListener('click', closePopup); }, {once: true}); }, 100); }
2. 编写Delphi Native Messaging宿主程序
这是一个Delphi控制台程序,负责和扩展通信、处理翻译:
program DelphiDictionaryHost; {$APPTYPE CONSOLE} uses SysUtils, Classes, JSON; procedure ReadNativeMessage(var InputJSON: string); var LengthBytes: array[0..3] of Byte; MsgLength: Integer; Buffer: TBytes; begin // 读取消息长度(Chrome Native Messaging用4字节无符号整数表示长度) Read(Input, LengthBytes, SizeOf(LengthBytes)); MsgLength := (LengthBytes[3] shl 24) or (LengthBytes[2] shl 16) or (LengthBytes[1] shl 8) or LengthBytes[0]; // 读取消息内容 SetLength(Buffer, MsgLength); Read(Input, Buffer, MsgLength); InputJSON := TEncoding.UTF8.GetString(Buffer); end; procedure SendNativeMessage(const OutputJSON: string); var LengthBytes: array[0..3] of Byte; MsgLength: Integer; Buffer: TBytes; begin // 发送消息长度 Buffer := TEncoding.UTF8.GetBytes(OutputJSON); MsgLength := Length(Buffer); LengthBytes[0] := MsgLength and $FF; LengthBytes[1] := (MsgLength shr 8) and $FF; LengthBytes[2] := (MsgLength shr 16) and $FF; LengthBytes[3] := (MsgLength shr 24) and $FF; Write(Output, LengthBytes, SizeOf(LengthBytes)); // 发送消息内容 Write(Output, Buffer, Length(Buffer)); Flush(Output); end; function TranslateWord(const Word: string): string; begin // 这里替换成你的翻译逻辑:比如查询本地词库、调用API等 if LowerCase(Word) = 'hello' then Result := '你好' else if LowerCase(Word) = 'world' then Result := '世界' else Result := '暂无翻译'; end; var InputJSON: string; JSONObj, ResponseObj: TJSONObject; Word: string; begin try while True do begin ReadNativeMessage(InputJSON); JSONObj := TJSONObject.ParseJSONValue(InputJSON) as TJSONObject; try if JSONObj.TryGetValue<string>('word', Word) then begin ResponseObj := TJSONObject.Create; try ResponseObj.AddPair('translation', TranslateWord(Word)); SendNativeMessage(ResponseObj.ToString); finally ResponseObj.Free; end; end; finally JSONObj.Free; end; end; except on E: Exception do begin // 处理异常,避免程序崩溃 Exit; end; end; end.
关键配置步骤
注册Native Messaging宿主:
在Windows系统中,需要在注册表中添加条目,让Chrome识别你的Delphi程序。创建一个注册表文件(比如register_host.reg):Windows Registry Editor Version 5.00 [HKEY_CURRENT_USER\Software\Google\Chrome\NativeMessagingHosts\com.yourcompany.delphidictionary] @="C:\\path\\to\\your\\host\\manifest.json"注意路径要换成你实际的宿主manifest文件路径。
宿主manifest文件:
创建一个host_manifest.json文件,放在Delphi程序同目录:{ "name": "com.yourcompany.delphidictionary", "description": "Delphi-powered Dictionary Host", "path": "DelphiDictionaryHost.exe", "type": "stdio", "allowed_origins": ["chrome-extension://<你的扩展ID>/"] }替换
<你的扩展ID>为你Chrome扩展的实际ID(加载扩展后在扩展管理页面可以看到)。
总结
通过这种“前端扩展+Delphi Native Messaging宿主”的方式,你就能实现类似Google Dictionary的功能:前端处理页面上的点击选中文本、弹窗展示,Delphi负责核心的翻译逻辑。这种方案既利用了Chrome扩展的页面交互能力,又能发挥Delphi在本地程序开发上的优势。
内容的提问来源于stack exchange,提问作者Peter Christian

