【发布时间】:2015-06-19 01:03:01
【问题描述】:
由于 NPAPI 弃用,我在使用 Java 应用程序和 Google Chrome 时遇到问题。 阅读一些文章和博客,我找到了一个“解决方案”:Native Messaging。
但是所有的例子都是用 C++/C#/Python 编写的,而对于 Java,什么都没有。 我想如果有人可以帮助我解决这个问题..
这是我的架构 (see image): 谷歌浏览器扩展 -> 原生消息 -> Java App (jar)
问题: 扩展程序调用 Java 应用程序,Java 应用程序运行但没有收到任何内容,当它返回时,扩展程序没有任何内容。
这是我的代码:
Chrome 扩展程序
background.js:
chrome.runtime.onConnect.addListener(function(port) {
port.onMessage.addListener(
function(message) {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
console.log( 'background.js received msg [' + message.text + ']');
console.log( 'port.postMessage({content: "generated by background.js"}); to [' + tabs[0].id + "/" + tabs[0].url + ']');
chrome.runtime.sendNativeMessage('cnb.digitalsigning',message,function(response) {
console.log("Received from native " + response);
});
chrome.tabs.sendMessage(tabs[0].id, {content: "generated by background.js"});
});
return true;
});
port.onDisconnect.addListener(function() {
console.log("Background.js Port disconnected");
});
});
//native messaging
content_script.js
window.addEventListener("message", function(event) {
// We only accept messages from ourselves
if (event.source != window)
return;
if (event.data.type && (event.data.type == "DIGITAL_SIGNER_MSG")) {
console.log("Content script received from webpage: " + event.data.text);
console.log('calling port.postMessage(event.data.text); ...' + event.data.text );
port = chrome.runtime.connect();
port.postMessage({text: event.data.text});
}
}, false);
chrome.runtime.onMessage.addListener(
function(response, sender, sendResponse) {
alert("receiving response from extension" + response.content );
});
manifest.json
{
"name": "Test",
"description": "Test",
"version": "0.1",
"manifest_version": 2,
"background": {
"persistent" : true,
"scripts": ["background.js"]
},
"content_scripts": [
{
"matches": ["*://*/*"],
"js": ["content_script.js"]
}
],
"permissions": [
"nativeMessaging"
]
}
HTML
<html>
<script>
function myFunc(){
console.log('call func');
window.postMessage({ type: "DIGITAL_SIGNER_MSG", text: "do it, baby!" }, "*");
console.log('func called');
}
</script>
<body>
<div>Page</div>
<form>
<button id="caller" onclick="myFunc()">Call Extension</button>
<div id="reponseDiv" style="border: 3px; border-color: blue;">NO RESPONSE LOADED</div>
</form>
</body>
</html>
主持人
installReg.bat
REG ADD "HKCU\Software\Google\Chrome\NativeMessagingHosts\digitalsigning" /ve /t REG_SZ /d "%~dp0digitalsigning.json" /f
pause
launch.bat
C:\location\to\Java\jre\bin\java.exe -cp C:\component\target\java.jar com.org.App
pause
digitalsigning.json
{
"name": "digitalsigning",
"description": "digitalsigning",
"path": "c:\\place\\launch.bat",
"type": "stdio",
"allowed_origins": [
"chrome-extension://<GOOGLE EXTENSION ID GENERATED>/"
]
}
应用程序包含一个 Main,它使用 System.in.read 捕获消息并使用 System.out.write 对扩展作出响应。
我该如何进行这种交流? 这是启动 java 应用程序的正确方法吗?
【问题讨论】:
标签: google-chrome native messaging npapi