Hello,
I am in the Android Webview team. I would like to receive some early feedback on potential improvements to Native App <-> JS communication in Android Webview (
http://developer.android.com/reference/android/webkit/WebView.html). In Chromium architecture, Android Webview is a layer above src/content and does not depend on src/chrome.
At present, applications using WebView can use addJavaScriptInterface() method to inject a Java object to JS context:
However this is not a very desirable method as it opens the application to malicious code when content is not trusted.
We are now investigating a mechanism that is closer to the existing standards. One potential API is designing sth similar to window.postMessage(message, targetOrigin, [transfer]). Without looking too much at the machinery underneath, I think the API can be sth like:
myObject.postMessage(message, targetOrigin)
where myObject is the name of the object injected to JS, message is the message and targetOrigin is the name of the application. Some questions to address are whether targetOrigin is really needed and if it is acceptable to have myObject being overloaded (a Java object vs. window).
Another option is using an API similar to chrome.runtime.sendNativeMessage(). This API is not really similar to how Webview objects interact, (i.e. it looks like the lifetime of native application is controlled by JS - Chrome starts application when a native message/communication is initiated from JS and destroys when not needed), but maybe we can create a Webview specific version that have different semantics.
The advantage of both APIs is they allow target and source origins to be enforced.
The Java side is more TBD but if we go with the first API, at the Java side we can create a public interface JsEventListener which is similar to EventListener in JS and then we can create a JsEvent class that will contain the data and origin.
interface JSEventListener {
void handleEvent(JsEvent event);
}
class JsEvent {
Object data;
String Url;
}
While I am going to further continue investigating it to come up with a more concrete proposal, I was wondering if there any suggestions, opinions and guidance both for the API and the machinery involved.
Thanks,
-Selim