I usually use the HTML5 PostMessage API to communicate information from my iframed content to the parent frame. Recently I\'ve had my content used inside an Android WebView (as
I was facing similar issue, I wanted to listen to .postMessage
event occuring in webview. I checked in raw html that the event was fired like this
window.parent.postMessage(JSON.stringify(message), '*');
Hence I dug more into postMessage and found this link for adding eventListener
window.addEventListener("message", receiveMessage, false);
function receiveMessage(event)
{
if (event.origin !== "http://example.org:8080")
return;
// ...
}
durban's answer helped me for setting up Android JS Interface.
Firstly a custom class for JavascriptInterface like this
class JsObject {
@JavascriptInterface
public void receiveMessage(String data) {
Log.i("JsObject", "postMessage data="+data);
//handle data here
}
}
Add javascriptInterface to webview before loading url/html
webView.addJavascriptInterface(new JsObject(), "Android"); //"Android" is just a name
Then call javascript in the onPageStarted
callback of WebViewClient
like below
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
webView.loadUrl("javascript:(function() {" +
"function receiveMessage(event) {\n" +
"Android.receiveMessage(JSON.stringify(event.data));\n" +
"}" +
"window.addEventListener(\"message\", receiveMessage, false);"+
"})()"
);
Log.i(TAG, "onPageStarted "+url);
}