Skip to content

JavaScript to Java communication

Endre edited this page Dec 28, 2019 · 3 revisions

JavaScript -> Java communication

The problem

One of the problems I faced by using JCEF is that there is no way to directly retrieve the return value of executed javascript code (at the time of writing). This meant that from our java API we had no way of knowing e.g. if an element is undefined, a textbox's current input value ect. I'd noticed that console messages were printed in sysout, but couldn't find any java code for it (and I'm too stubborn to edit the native files). As i kept looking around i found a solution similar to my original idea.

The solution

I found the interface CefJSDialogHandler, which handles javascript dialogs (alert, prompt & confirm). In the method onJSDialog site url, dialog text and dialog type are all exposed. By default the method makes a new window pop up with data according to what's passed, but the popup can be suppressed by changing the value of the BoolRef parameter. This means we have a one-way communication line from javascript to java.

The implementation

This resulted in the BrowserJSDialogListener class. It works by having elements execute prompt("AutoChrome " + ID + VALUE) as javascript. ID is used to be able to identify the element who reqeuested the value because all values are piped through the same message. VALUE is replaced with whatever javascript code is used to get the needed value. BrowserJSDialogListener's task is simply to identify these prompts and foward them to the JSVariableBridge class. The bridge class contains a map of IDs and their respective element object. When an ID and a value is passed to the onVariable method the program will look for the passed ID and if found, removes the element from the queue map and calls onJavaScriptValue in the Element class. onJavaScriptValue currently just sets the javaScriptValue field, but could have other uses in the future. The element object has until this point waited for javaScriptValue to receive a value, and can now present the value.

Flow chart of the process: Flow chart

Possible implications

Because the javascript to java communication effectively relies on javascript being executed a website could break AutoChrome scripts by spamming invalid prompts. This however seems unlikely as the site first has to correctly identify the browser as AutoChrome, and prompt data is validated before being handled.

Clone this wiki locally