在Chrome原生消息传递:有多长是本地应用实例对象的生命周期

In Chrome Native messaging: how long is the native app instance object lifetime?

本文关键字:实例 应用 对象 周期 生命 消息传递 原生 Chrome      更新时间:2023-09-26

与Chrome扩展对话的本机应用程序是否永远存在?我的意思是,它是否应该出现,例如在回发发生之前?我找不到任何可以在清单文件中添加的配置。

我有一个页面,页面上有一些物体。在点击一个对象并使用Native应用程序发送/接收一条消息后,它就不再适用于其他对象。

我的确切问题:本机应用程序实例对象生命周期有多长?对象应该永远响应吗?或者我需要一个循环,例如从stdin读取消息,如果这是一个连续的通信?

这是我的背景脚本:

var host_name = "files.mffta.java.nativeapp";
var port = null;
initPort();
function initPort() {
    console.log( 'Connecting to native host: ' + host_name );
    port = chrome.runtime.connectNative( host_name );
    port.onMessage.addListener( onNativeMessage );
    port.onDisconnect.addListener( onDisconnected );
}
// Listen for messages that come from the content script.
chrome.runtime.onMessage.addListener(
  function( messageData, sender, sendResponse ) {
    if( messageData ) {
        sendNativeMessage(messageData);
        sendResponse( { res: 'done!' } );
    }
  } );
// Sending a message to the port.
function sendNativeMessage(messageData) {
    if( port == null )
        initPort();
    console.log( 'Sending message to native app: ' + JSON.stringify( messageData ) );
    port.postMessage( messageData );
    console.log( 'Sent message to native app.' );
}
// Receiving a message back from the Native Client API.
function onNativeMessage( message ) {
    console.log( 'recieved message from native app: ' + JSON.stringify( message ) );
    alert( "messaged received from Native: " + JSON.stringify( message ) );
    //sending a message to Content Script to call a function
    if( message.methodName && message.methodName != "" ) {
        chrome.tabs.query( { active: true, currentWindow: true }, function( tabs ) {
            chrome.tabs.sendMessage( tabs[0].id, message, function( response ) {
                // Call native again to return JavaScript callback function results
                alert ("calc res received by extension : " + response);
                sendNativeMessage({ type: "JSCallbackRes", callbackRes: response });
            } );
        } );
    }
}
// Disconnecting the port.
function onDisconnected() {
    console.log( "ERROR: " + JSON.stringify( chrome.runtime.lastError ) );
    console.log( 'disconnected from native app.' );
    port = null;
}

我的扩展清单:

{
  "name": "Files.ChromeExt.Operarations",
  "version": "1.0",
  "manifest_version": 2,
  "description": "This extension calls a Native API which that API calls some x-Files related operations.",
  "icons": {
    "128": "x-files_icon.png"
  },
  "permissions": [
    "nativeMessaging", "activeTab"
  ],
  "background": {
    "persistent": true,
    "scripts": ["main.js"]
  },
  "content_scripts" : [{"matches": ["http://localhost/*","https://localhost/*"], 
    "js": ["contentscripts/page.js"]}]
} 

Java程序: [as has been asked in comments]

import java.io.IOException;
import javax.swing.JOptionPane;
public class Applet {
    public Applet(){}
    public static void main(String[] args) {
        try {
            readMessage();
            sendMessage("{'"msg'" : '"hello'"}");
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        }
    }
    public static 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 static 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");
        }
    }
}

通过检查chrome日志,我可以看到这些消息:

  • 本机消息主机试图发送一个1936028240字节长的消息。
  • {"message":"与本机消息传递主机通信时出错。"}",来源:chrome-extension://XXX

我正在一台64位的win8.0机器上测试这些。

更新:我现在确信,如果调用connectNative并且端口没有因错误而停止,则主机将永远存活。因此,上述错误消息的根本原因一定不是端口生命周期。我的意思是,我的通信中出现了一些错误,强行停止了端口。

我非常感谢你给我的任何意见。

如果使用chrome.runtime.sendNativeMessage,本地应用程序将在收到消息后和发送消息之前出现。由于消息的接收是异步的,所以当sendNativeMessage的回调被调用时,您不能假设应用程序仍然存活。

如果你想确保本地应用程序停留更长时间,使用chrome.runtime.connectNative。这将创建一个端口,并且本机应用程序将处于活动状态,直到它退出或直到扩展在端口上调用disconnect()。如果你的应用程序意外地提前终止,那么你很可能在本地消息传递协议的实现中犯了错误。

本机消息传递协议的确切格式,请查看文档:https://developer.chrome.com/extensions/nativeMessaging native-messaging-host-protocol


对于您的编辑,错误消息非常清楚:长度无效。长度应该是系统的本机字节顺序(可以是小端序或大端序)。当您收到以下错误消息,其中偏移量差异过大时,有两种可能性:

  1. 整数字节顺序错误,或
  2. 你的输出包含一些意想不到的字符,这导致字节移位,导致字节位于错误的位置。

要知道您所处的情况,请查看十六进制数。如果后面有很多零,则表明字节顺序不正确。例如,如果您的消息长度为59,则十六进制值为3b。如果端序不正确,则显示如下信息:

本机消息主机尝试发送989855744字节长的消息。

1493172224是十六进制的3b 00 00 00,您可以观察到3b在那里,但是在错误的一端(换句话说,字节顺序颠倒了)。对于您的系统,解决这个问题的方法是编辑代码,使其以相反的顺序打印字节。

如果号码的十六进制视图看起来与您的号码不太接近,则消息长度可能不正确。回想一下,stdio是用于通信的,所以如果你输出任何其他东西(例如错误)到stdout (System.out)而不是stderr (System.err),那么协议就被违反了,你的应用程序将被终止。

        System.err.println(ex.getStackTrace());                     // <-- OK
        System.out.println("[ error -> " + ex.getMessage() + " ]"); // <-- BAD

在Windows上,还要检查是否将标准输出(和标准输入)的模式设置为O_BINARY。否则,Windows将在0A (0D 0A)之前插入一个额外的字节,这将导致所有字节移位并且数字不正确。Java运行时已经支持二进制模式,所以对于您的情况,它不相关。