实现Firefox扩展程序,和Java RMI Client端进行通信。
在Firefox工具栏注册按钮,点击按钮后弹出Popup.html页面,引用Popup.js脚本,通过脚本向Java RMI client发送消息,Java RMI Client接收消息后转发到Java RMI Server。
Popup.js中的发送代码:
btnSend.addEventListener("click", function(event) {
const sending = browser.runtime.sendNativeMessage("native.host", url.value);
sending.then(function(resp) {
txtResult.textContent = resp.message;
}, function(err) {
txtResult.textContent = err;
});
});
注册的native.json配置文件
{
"name": "native.host",
"description": "Example host for native messaging",
"path": "native.bat",
"type": "stdio",
"allowed_extensions": ["hook@native"]
}
执行的native.bat代码
@echo off
rem echo off -> close stdout
call java -cp "C:\Users\cc\OneDrive\src\java\RMIClient\bin" net.RMIClient
Java RMI client程序
public class RMIClient {
public static String read() throws IOException {
byte[] _len = new byte[4];
System.in.read(_len);
ByteBuffer bb = ByteBuffer.wrap(_len);
bb.order(ByteOrder.LITTLE_ENDIAN);
int length = bb.getInt(0);
byte[] message = new byte[length];
System.in.read(message);
return new String(message, "UTF-8");
}
public static void write(String s) throws IOException {
byte[] utf = s.getBytes("UTF-8");
ByteBuffer bb = ByteBuffer.allocate(utf.length + 4);
bb.order(ByteOrder.LITTLE_ENDIAN);
bb.putInt(0, utf.length);
bb.put(4, utf);
byte[] bs = bb.array();
System.out.write(bs);
System.out.flush();
}
public static void main(String[] args) throws IOException, InterruptedException, NotBoundException {
Registry registry = LocateRegistry.getRegistry("127.0.0.1", 1099);
IReceive receiver = (IReceive) registry.lookup("Receiver");
String data = read();
String result = receiver.receive(data);
write(" { \"message\":\"ok\" }" );
}
}
运行效果,浏览器弹出框,点击"Send"发送浏览器当前地址
Java RMI Server收到的消息: