How do you process a Chrome Native Messaging API-call with a bash script?
I succeeded in doing it with python with this example
Sure I can call bash
from the python code with subprocess
, but is it possible to skip python and process the message in bash
directly?
The problematic part is reading the JSON serialized message into a variable. The message is serialized using JSON, UTF-8 encoded and is preceded with 32-bit message length in native byte order through stdin.
echo $*
only outputs:
chrome-extension://knldjmfmopnpolahpmmgbagdohdnhkik/
Also something like
read
echo $REPLY
doesn't output anything. No sign of the JSON message. Python uses struct.unpack
for this. Can that be done in bash
?
I suggest to not use (bash) shell scripts as a native messaging host, because bash is too limited to be useful.
read
without any parameters reads a whole line before terminating, while the native messaging protocol specifies that the first four bytes specify the length of the following message (in native byte order).Bash is a terrible tool for processing binary data. An improved version of your
read
command would specify the-n N
parameter to stop reading afterN
characters (note: not bytes) and-r
to remove some processing. E.g. the following would store the first four characters in a variable calledvar_prefix
:Even if you assume that this stores the first four bytes in the variable (it does not!), then you have to convert the bytes to an integer. Did I already mention that bash automatically drops all NUL bytes? This characteristics makes Bash utterly worthless for being a fully capable native messaging host.
You could cope with this shortcoming by ignoring the first few bytes, and start parsing the result when you spot a
{
character, the beginning of the JSON-formatted request. After this, you have to read all input until the end of the input is found. You need a JSON parser that stops reading input when it encounters the end of the JSON string. Good luck with writing that.Generating output is a easier, just use
echo -n
orprintf
.Here is a minimal example that assumes that the input ends with a
}
, reads it (without processing) and replies with a result. Although this demo works, I strongly recommend to not use bash, but a richer (scripting) language such as Python or C++.