Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: click within WebView causes callback to Android application

I'm thinking of implementing a HTML welcome panel to our Android app, which presents news and offers on the start-up screen. My question is now, if I present an offer to a specific place (with an id string) can I trigger a callback from the WebView (maybe via Java Script) to the Android app and passing that id string to make it start a new Activity which loads and shows data from a server (JSON) depending on that id string?

The second part is already implemented and working. My main concern is how to get the id string from the HTML WebView back to the Android app when the user clicks on it.

We prefer to use a WebView for that specific welcome panel, because it gives us more flexibility to customize by using HTML.

like image 884
znq Avatar asked Jun 17 '26 09:06

znq


2 Answers

It's probably better to use WebView.addJavascriptInterface, rather than overload onJsAlert.

like image 127
Bruce Christensen Avatar answered Jun 19 '26 02:06

Bruce Christensen


yes indeed you can good sir! If you show the data in a javascript Alert, then you can capture it like this. It might not be the most neat way, but it works =)

private void loadWebViewStuff() {
        myWebView.setWebChromeClient(new MyWebChromeClient());
        myWebView.loadUrl(URL);
}


final class MyWebChromeClient extends WebChromeClient {
    @Override
    public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
        //"message" is what is shown in the alert, here we can do whatever with it
    }
}
like image 38
pgsandstrom Avatar answered Jun 19 '26 00:06

pgsandstrom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!