Android4.2以前WebView 提供了javascript 调用Java代码的方法,会造成很大的安全漏洞。Android官方在
API17
后,限制javascript代码只能调用声明了@JavascriptInterface
注解的Java方法。
所以必须要给每个可供js代码调用的Java方法加一个
@JavascriptInterface
接口。1
//js调用代码
w.settings.javaScriptEnabled = true
w.addJavascriptInterface(GetHTMLContent(), "lt")
w.webViewClient = MyWebViewClient()
w.loadUrl("javascript:lt.showh(document.getElementsByTagName('html')[0].innerHTML);")
//调用的方法
class GetHTMLContent {
@JavascriptInterface
fun showh(html: String) {
Log.d("HTML", html)
}
}