For the More Curious: Injecting JavaScript Objects

In this chapter, you have seen how to use WebViewClient and WebChromeClient to respond to specific events that happen in your WebView. However, it is possible to do even more by injecting arbitrary JavaScript objects into the document contained in the WebView itself. Check out the documentation at developer.android.com/​reference/​android/​webkit/​WebView.html and scroll down to the addJavascriptInterface(Object, String) function. The documentation uses Java method signatures, but remember that Object is equivalent to Any in Kotlin. Using this, you can inject an arbitrary object into the document with a name you specify:

 webView.addJavascriptInterface(object : Any() { @JavascriptInterface ...

Get Android Programming: The Big Nerd Ranch Guide, 4th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.