How to pass a byte array (byte[]) from java to javascript in jxbrowser

739 Views Asked by At

Does anyone know if and how it is possible to pass a byte[] from java to javascript in jxbrowser?
(The goal is to open a binary file in the browser without a file chooser dialog popping up).
When I try to pass the byte[] natively:

Java:

                JsFunction function = frame.executeJavaScript("openFileContent");
                byte[] blob = new byte[3];
                blob[0] = 10;
                blob[1] = 20;
                blob[2] = 30;
                return function.invoke(instance, blob);

Javascript:

    openFileContent = function(fileContent) {
        console.log(fileContent);
        console.log(fileContent[0]);

On the javascript side, I get:

[object [B]
undefined

So it doesn't look like it gets marshalled into anything usable.
My other approach was wrapping the blob into a POJO, like:

    public static class JsBlob {
        private byte[] buffer;

        public JsBlob(byte[] buffer) {
            this.buffer = buffer;
        }

        @JsAccessible
        public byte get(int index) {
            return buffer[index];
        }

        @JsAccessible
        public byte[] getBuffer() {
            return buffer;
        }

        @JsAccessible
        public int getLength() {
            return buffer.length;
        }
    }

Which -while working- was super slow because of all the inter process calls when getting the actual array contents, byte-by-byte.

My current fallback is transferring the base64 encoded blob in a String, which does get properly marshalled as string, then decoding it on the js side, but if possible, I'd like to avoid this unnecessary processing, if possible.

1

There are 1 best solutions below

2
Vladimir On

Support of the JavaScript arrays is on the product roadmap: https://jxbrowser-support.teamdev.com/roadmap/

So, this functionality will be supported in one of the next versions. You can follow JxBrowser on Twitter to find out when this feature is released: https://twitter.com/JxBrowserTeam

UPD: JxBrowser 7.20 and higher supports JavaScript Array, Set, Map, and ArrayBuffer. Read more at https://jxbrowser-support.teamdev.com/release-notes/2021/v7-20.html#javascript