Post message via javascript to browserframe

Hi Support

I have an BrowserFrame that displays a BI Dashboard. I would like to use
iframe.contentWindow.postMessage(JSON.stringify({key: val, key2: val, ...}))
to update the data in the iframe when my user selects a value from a lookup field or other control on the page.

Should I use AbstractJavaScriptExtension to achieve this or there a better approach?

Thanks

Hi,

Yes, using AbstractJavaScriptExtension would be the best way, as if you pass some parameters to your function, Vaadin will escape them properly for you.

You can see an example here GitHub - cuba-labs/js-extension: Example of extending of existing UI component using JavaScript extension

In my-extension.js add

self.update = function (param1, ...) {
    iframe.contentWindow.postMessage(JSON.stringify({key: val, key2: val, ...}))
}

In MyExtension.java add

public void update(String param1,...) {
    callFunction("update", param1,...);
}
1 Like

@shustanov
Thanks for the confirmation and the sample code!

Hi @shustanov

I got the postMessage to the Iframe working exactly how i want it. I also need to listen for postMessage events in my CUBA page from the iframe.

in my-extension.js i have:

window.addEventListener("message", function(event) {
 console.log("!!!! event", JSON.parse(event.data));
});

This isn’t not working. It could be that the Iframe is not submitting the event but I wanted to make sure there was not something happening on the vaadin side.

@herby it really looks like iframe doesn’t properly submit the event.

Check if you correctly specified targetOrigin and if you invoke it on correct window object.

You can set targetOrigin to * just for test, but it is not desirable in production for security reasons.

Also ensure that listener is registered correctly by sending an event from window to itself with developer console.

Hi @shustanov

You were correct. I had a small misconfiguration. One last thing, what is the best way to communicate the event details back to the CUBA backend from the javascript event handler? Can you provide a quick code example?

Thanks

Hi @herby

For this purpose you can register JavaScriptFunction inside your extension, that would be invoked from the client side js code.

In MyExtension.java constructor add

addFunction("updateCUBA", new JavaScriptFunction() {
            @Override
            public void call(JSONArray arguments) throws JSONException {
//              Do your stuff here
            }
});

In my-extension.js code you can invoke it inside the message listener:

window.addEventListener("message", function(event) {
 self.updateCUBA(...);
});
1 Like