Search code examples
ioscodenameone

Codename One - how to create webview communicate with native (iOS)


I am creating an mobile app which UI must be in html/reactjs and business logic must be in Java. Codename One is good option but its UI is Swing alike, so I am thinking can I load the local html onto the webview and let it communicates with the native code (Java) in Codename One?

I found this API BrowserComponent, I am going to attach the RESTful request and response in the browser window object, and use it to communicate via BrowserComponent API.

From native code (Java) to execute Javascript in webview, I found this API, but from webview to execute native code (Java), is there a way to do so?


Solution

  • You use a navigation listener and then navigate to a well known URI which you can then map to what you want. See addBrowserNavigationCallback. With that you can write code in the callback such as:

    bc.addBrowserNavigationCallback(url -> {
          switch(url) {
              case "method1://invoke": 
                  callSerially(() -> method1()); 
                  return false;
              case "method2://invoke": 
                  callSerially(() -> method2()); 
                  return false;
          }
          return true;
    });
    

    You can pass arguments in the call which will make this code a but more complex but the gist is the same.

    Notice that callSerially is essential here since this method exposes the browser navigation thread and blocks it. You shouldn't grab that thread.