JavaScript to Unity SendMessage string truncated, null-terminated

I found this problem when trying to send binary data from the browser to Unity through the string argument of the unityInstance.SendMessage function. Although the JavaScript portion of my code has no problem with null characters in a string variable, and the receiving C# portion of the code should (according to some light research) be able to handle it as well, somewhere between the two the string gets terminated at the first point of a null character.

This might be expected behaviour, I don’t know, but I couldn’t find it documented anywhere and it was a real headscratcher for me. My colleague had similar problems with SendMessage functions where the entire message was not being sent. However, those calls were internal to Unity, and didn’t interact with the WebGL part. He found some workaround though, so I cannot confirm that it was the same issue.

Simplified code example

var bin = new Uint8Array();
bin = [97,98,99, 0, 49,50,51,61];
let text = bin2String(bin);
console.log("Conversion is: " + text);
unityInstance.SendMessage("WebInterface", "receiveBinary", text);
public void receiveBinary(string text){
        Debug.Log("Inputted string: " + text);
        Debug.Log("String length: " + text.Length);
}

Output:

Inputted string: abc
String length: 3

Note: Added the white box in the output for this post manually, as that is what the browser log shows, but this forum does not display null characters that way

Did you ever find a solution to this? I am experiencing the exact same issue Unity 2018

Same Issue, @Fizzr and @diaosuyi Did either of you find a solution?

When you want to send binary data as string, it’s better to use a bin to text encoding, like base64.

and if you need to send binary data from JS to Unity C# there are other ways instead of SendMessage.
You can create byte array in Unity, and share it’s size and pointer position to JS, and then fill it in JS.