For the More Curious: Injecting JavaScript Objects

We saw how to use WebViewClient and WebChromeClient to respond to specific events that happen in your WebView. However, it is possible to do even more than that by injecting arbitrary JavaScript objects into the document contained in the WebView itself. Check out the documentation at http://​developer.android.com/​reference/​android/​webkit/​WebView.html and scroll down to the addJavascriptInterface(Object,String) method. Using this, you can inject an arbitrary object into the document with a name you specify.

m​W​e​b​V​i​e​w​.​a​d​d​J​a​v​a​s​c​r​i​p​t​I​n​t​e​r​f​a​c​e​(​n​e​w​ ​O​b​j​e​c​t​(​)​ ​{​ ​ ​ ​ ​p​u​b​l​i​c​ ​v​o​i​d​ ​s​e​n​d​(​S​t​r​i​n​g​ ​m​e​s​s​a​g​e​)​ ​{​ ​ ​ ​ ​ ​ ​ ​ ​L​o​g​.​i​(​T​A​G​,​ ...

Get Android Programming: The Big Nerd Ranch Guide 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.