在我的 Java 程序中,这是 Chrome extension's host (或 native 应用程序),每次我的 Chrome 扩展程序调用主机时,都会创建我的 Applet 类的新实例。
如何防止这种情况发生?我的意思是,我需要为所有主机-扩展-主机调用提供一个单独的 Applet 对象,如何实现这一目标?
这是我的程序:
import javax.swing.JOptionPane;
public class Applet {
static Applet myApplet;
public Applet(){
System.err.println("new instance created!");
}
public static void main(String[] args) {
try {
if (myApplet == null)
myApplet = new Applet();
myApplet.readMessage();
myApplet.sendMessage("{\"data\": \"somee data\"}");
} catch (Exception ex) {
System.err.println("error");
JOptionPane.showMessageDialog(null, ex.getMessage());
}
}
public String readMessage() {
String msg = "";
try {
int c, t = 0;
for (int i = 0; i <= 3; i++) {
t += Math.pow(256.0f, i) * System.in.read();
}
for (int i = 0; i < t; i++) {
c = System.in.read();
msg += (char) c;
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "error in reading message from JS");
}
return msg;
}
public void sendMessage(String msgdata) {
try {
int dataLength = msgdata.length();
System.out.write((byte) (dataLength & 0xFF));
System.out.write((byte) ((dataLength >> 8) & 0xFF));
System.out.write((byte) ((dataLength >> 16) & 0xFF));
System.out.write((byte) ((dataLength >> 24) & 0xFF));
// Writing the message itself
System.out.write(msgdata.getBytes());
System.out.flush();
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "error in sending message to JS");
}
}
}
我相信不需要添加任何扩展程序或 background.js 代码,但如果您也需要查看这些代码,请告诉我。
非常感谢。
最佳答案
首先 - 使用chrome.runtime.connectNative
而不是chrome.runtime.sendNativeMessage
(example)。
在您的 native 应用程序 (Java) 中,使用无限循环来不断接收消息。目前,您仅接收和发送消息。之后,没有发生任何其他事情,因此您的应用程序可以理解地退出。 stdio native messaging protocol非常简单:
- 读取 32 位消息长度( native 字节顺序)。
- 读取 JSON 编码的消息(长度如之前指定)。
- 写入 32 位消息长度( native 字节顺序)。
- 编写 JSON 编码消息(长度如之前指定)。
- 重复此操作,直到任一端断开端口连接。
您的程序应该包含一个实现上述协议(protocol)的(无限)循环。这是一个具有所需流程的程序结构:
class Applet {
public static void main(String[] args) {
new Applet(); // Initialize application.
}
Applet() {
while (true) {
readMessage();
// ... and save the state for later processing if needed
// Send the reply:
sendMessage("{\"data\": \"somee data\"}");
}
}
// TODO: Implement readMessage and sendMessage (see question).
}
关于javascript - 如何防止每次调用主机时都创建该类的新实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31669420/