如何将shell脚本用作Chrome Native Messaging主机应用程序

Jan*_*hou 6 bash json google-chrome-extension chrome-native-messaging

如何使用bash脚本处理Chrome Native Messaging API调用?

我用这个例子成功地用python做了

当然我可以bash从python代码调用subprocess,但是可以跳过python并bash直接处理消息吗?

该问题的部分被读取JSON序列化消息到变量中.消息使用JSON,UTF-8编码进行序列化,并且在本地字节顺序之前通过stdin以32位消息长度开头.

echo $* 只输出: chrome-extension://knldjmfmopnpolahpmmgbagdohdnhkik/

还有类似的东西

read
echo $REPLY
Run Code Online (Sandbox Code Playgroud)

不输出任何东西.没有JSON消息的迹象.Python struct.unpack用于此.可以这样做bash吗?

Rob*_*b W 7

我建议不要将(bash)shell脚本用作本机消息传递主机,因为bash太有限而无法使用.

read没有任何参数在终止之前读取整行,而本机消息传递协议指定前四个字节指定后续消息的长度(以本机字节顺序).

Bash是处理二进制数据的糟糕工具.read命令的改进版本将指定-n N在N字符后停止读取的参数(注意:不是字节)并-r删除某些处理.例如,以下内容将前四个字符存储在一个名为的变量中var_prefix:

IFS= read -rn 4 var_prefix
Run Code Online (Sandbox Code Playgroud)

即使你假设它存储了变量中的前四个字节(它没有!),那么你必须将字节转换为整数.我是否已经提到bash会自动丢弃所有NUL字节?这种特性使得Bash完全没有价值,因为它是一个功能齐全的本机消息传递主机.

您可以通过忽略前几个字节来应对这个缺点,并在发现{字符(JSON格式的请求的开头)时开始解析结果.在此之后,您必须读取所有输入,直到找到输入结束.您需要一个JSON解析器,当它遇到JSON字符串的结尾时停止读取输入.写这篇文章祝你好运.

生成输出更简单,只需使用echo -n或printf.

这是一个最小的例子,假设输入以a结束},读取(不处理)并回复结果.虽然这个演示有效,但我强烈建议不要使用bash,而是使用更丰富的(脚本)语言,如Python或C++.

#!/bin/bash
# Loop forever, to deal with chrome.runtime.connectNative
while IFS= read -r -n1 c; do
    # Read the first message
    # Assuming that the message ALWAYS ends with a },
    # with no }s in the string. Adopt this piece of code if needed.
    if [ "$c" != '}' ] ; then
        continue
    fi

    message='{"message": "Hello world!"}'
    # Calculate the byte size of the string.
    # NOTE: This assumes that byte length is identical to the string length!
    # Do not use multibyte (unicode) characters, escape them instead, e.g.
    # message='"Some unicode character:\u1234"'
    messagelen=${#message}

    # Convert to an integer in native byte order.
    # If you see an error message in Chrome's stdout with
    # "Native Messaging host tried sending a message that is ... bytes long.",
    # then just swap the order, i.e. messagelen1 <-> messagelen4 and
    # messagelen2 <-> messagelen3
    messagelen1=$(( ($messagelen      ) & 0xFF ))               
    messagelen2=$(( ($messagelen >>  8) & 0xFF ))               
    messagelen3=$(( ($messagelen >> 16) & 0xFF ))               
    messagelen4=$(( ($messagelen >> 24) & 0xFF ))               

    # Print the message byte length followed by the actual message.
    printf "$(printf '\\x%x\\x%x\\x%x\\x%x' \
        $messagelen1 $messagelen2 $messagelen3 $messagelen4)%s" "$message"

done
Run Code Online (Sandbox Code Playgroud)