如何在Chrome Native Messaging主机上解析stdin中的JSON?

时间:2018-01-24 02:38:46

标签: javascript bash chrome-native-messaging

相关:

利用How do I use a shell-script as Chrome Native Messaging host application处的代码将JSON从客户端(app)发送到主机

#!/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
    # do stuff
    message='{"message": "'$c'"}'
    # 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

导致

{"message":"}"}

在客户端应用程序中收到。

循环显然不会捕获$c循环中的变量while

使用来自客户端的JSON输入

{"text":"abc"}

使用JavaScript,我们可以通过检查前后索引

中的字符来获取JSON字符串的单个属性

&#13;
&#13;
var result = "";
var i = 0;
var input = '{"text":"abc"}';
while (i < input.length) {

  if (input[i - 2] === ":" && input[i - 1] === '"' || result.length) {
    result += input[i];
  }

  if (input[i + 1] === '"' && input[i + 2] === "}") {
    // do stuff
    break;
  }
  
  ++i;
  
};

console.log(result);
&#13;
&#13;
&#13;

尚不确定如何将if条件转换为来自JavaScript的bash以获取上述代码匹配的单个JSON属性并连接到How do I compare two string variables in an 'if' statement in Bash?How to concatenate string variables in Bash?之后的字符串。如果条件需要为传递给主机的特定JSON多次调整代码,则给定具有嵌套属性的JSON对象使用嵌套或多个。

documentation描述协议

  

原生邮件协议

     

Chrome会在单独的进程中启动每个本机消息传递主机   使用标准输入(stdin)和标准输出与它通信   (标准输出)。相同的格式用于在两个方向上发送消息:   每个消息都使用JSON,UTF-8编码并序列化   以原生字节顺序的32位消息长度。

无法在SO找到任何答案,这些答案明确描述了使用bash在Chrome Native Messsaging应用程序主机上从stdin解析JSON的过程。

如何创建通用解决方案或算法(包括协议和语言所需的每个步骤的描述)来解析从stdin主机上的客户端发送的JSON,获取并设置正确的32位将使用bash将JSON响应消息的本机字节顺序的消息长度(例如echo; printf)发送到客户端?

0 个答案:

没有答案