chrome瀏覽器自從去年以來逐步去掉了對瀏覽器插件的支持,npapi的方案馬上不可用。 當務之急要選擇一個替代方案,最常用的就是擴展了。擴展程序提供了一套和本地程序交互的方案——“原生消息通信”
寫本地應用的工具和語言很多,比如:C#,C++,phyon 都可以,本人對delphi熟悉一點,就說說delphi怎么接收和發送消息的吧。
Chrome擴展對原生消息通信有非常明確的說明
Chrome 瀏覽器在單獨的進程中啟動每一個原生消息通信宿主,並使用標准輸入(stdin)與標准輸出(stdout)與之通信。向兩個方向發送消息時使用相同的格式:每一條消息使用 JSON 序列化,以 UTF-8 編碼,並在前面附加 32 位的消息長度(使用本機字節順序)。
怎么做呢?
1、background.js中定義消息
var nativeHostName='com.xxx.mytest'; //chrome與本地程序通信的橋梁,根據該名稱進行配置項的尋找。windows下在注冊表HKEY_CURRENT_USER\Software\Google\Chrome\NativeMessagingHosts內尋找,linux下在目錄/etc/opt/chrome/native-messaging-hosts/尋找該名稱的json文件() //native start chrome.runtime.sendNativeMessage(nativeHostName,jsonData, function(response){ if (chrome.runtime.lastError){ console.log("lastError:" + chrome.runtime.lastError.message); } else{ console.log("recieved message: ", response.message); } });
2、新建一個Delphi控制台程序,添加標出輸入和標准輸出接口即可
接收數據的標准輸入
function ReadInputJson():WideString; var strmInput: THandleStream; LBuffer: TBytes; resLen:Integer; sData: string; begin strmInput := THandleStream.Create(GetStdHandle(STD_INPUT_HANDLE)); try SetLength(LBuffer, 4); strmInput.ReadBuffer(Pointer(LBuffer)^,4); resLen:= PInteger(LBuffer)^; SetLength(sData, resLen); strmInput.Read(sData[1], resLen); Result := UTF8Decode(sData); finally strmInput.Free; end; end;
返回數據的標准輸出
procedure WriteOutputJson(const str:String); var strmOut: THandleStream; len:Integer; json:String; begin json:=UTF8Encode(str); len:=Length(json); strmOut := THandleStream.Create(GetStdHandle(STD_OUTPUT_HANDLE)); try strmOut.Write(len,4); strmOut.Write(PChar(json)^, len); finally strmOut.Free; end; end;
主要是處理UTF8編碼和前32位長度,非常容易出錯。