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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.