Member-only story
Learn Once Use Everywhere: Using JavaScript APIs in Java for Web Browser
Last time we saw how we can reuse our Java code in JavaScript from my article “Web Browser Programming in Java”. Today we’ll take a look on how we could call the JavaScript APIs, web apps and frameworks from our Java code and at the end to transpile them back to JavaScript so that it will be runnable on the web browser.
To see how we could do this, it is important that we understand the process on how Java with GWT (http://www.gwtproject.org) or J2CL (https://github.com/google/j2cl) communicates with JavaScript. For this purpose we have the JsInterop which work as a bridge between Java and JavaScript. In the old version of GWT we had JSNI (JavaScript Native Interface) but this is now deprecated and we should only use JsInterop. In JsInterop you have two cases:
Use case 1: the contracts are available in Java and you want to use those contracts in JavaScript. This is shown in our Calculator example from my first article. In this case you want to use the Java apps and APIs from your JavaScript apps.
Use case 2: the contracts are available in JavaScript as APIs or apps or frameworks and you want to use them in Java. In this case you need to bridge the JavaScript APIs to your Java apps. At the end you transpile everything back to JavaScript since you want to run your app on the web browser.
Following picture shows both use cases for JsInterop.