I have some HTML5/javascript files hosted on a server. When a button is clicked on the HTML5 page a javascript function is invoked. I want to listen for when a function is invoked and get the json that the function returns. Previously I was opening a port on the device but that doesn’t seem to work on Android 3.0. I have heard that you can use external interface to listen to javascript calls but I don’t know how to implement that.
Share
To use external interfaces you need to run your site in WebView. Also the following solution implies, what
To register your interface you need to call the addJavascriptInterface method on your
WebViewinstance. You need to select a name for it and create an implementation. Your interface should intercept function calls and report their results, so, let’s describe it…and register it…
For more information on JavaScript interface see Binding JavaScript
Then you need to “transfer” function results to your interface… Here you need some JavaScript code.
To wrap your function use this code
Also, don’t forget to enable JavaScript at all
When, how to embed this code to your external page (I imply what you are not having access to external JS code)… To execute arbitrary code in the page context you can use loadUrl method of
WebViewThis will not trigger page reload, just JavaScript will be executed. Note what you need to execute this after page is fully loaded. You can obtain this by code below:
See setWebViewClient and onPageFinished for details
Also note, what code, transferred to page via
loadUrlcall, must not contain line breaks. So you need to get rid of them (by String.replace or so).ADD
So, the final solution is: