我想使用Android WebView单击html页面中的特定按钮。
我有这个html:
<div class="card">
<div class="card-header" id="block2">
<button type="button" class="btn bld-no-btn" aria-expanded="true" aria-controls="item2" data-toggle="collapse" data-target="#item2">
<div class="d-flex align-items-center">
<i class="icon small blue icon-arrow pr-3" aria-hidden="true">delta_omhoog</i>
<h3>Title of button</h3>
<div class="ml-auto pr-0 pr-md-3">
<i class="icon red px-1" title="waarschuwing">waarschuwing</i>
</div>
</div>
</button>
</div>
我已经将其托管在这里:http://www.jimclermonts.nl/test/
我已编写此代码来单击按钮
class MainActivity : AppCompatActivity() {
lateinit var webView: WebView
var firstTime: Boolean = true
companion object {
const val JAVA_SCRIPT =
"javascript:window.HTMLOUT.processHTML('<html>'+document.getElementsByTagName('html')[0].innerHTML+'</html>');"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
webView = findViewById(R.id.webView)
initializeWebView("http://www.jimclermonts.nl/test/")
}
@SuppressLint("JavascriptInterface", "SetJavaScriptEnabled")
private fun initializeWebView(url: String?) {
class JavaScriptTokenSubstractInterface {
@JavascriptInterface
@SuppressWarnings("unused")
fun processHTML(html: String) {
// check if html is correct
webView.loadUrl(
"javascript:(function() {" +
"document.getElementById(\"item2\").querySelectorAll(\"button\")[0].click();" +
"})()"
)
}
}
webView.webChromeClient = object : WebChromeClient() {
override fun onConsoleMessage(message: String, lineNumber: Int, sourceID: String) {
Log.d("MyApplication", "$message -- From line $lineNumber of $sourceID")
}
}
webView.settings.javaScriptEnabled = true
webView.settings.useWideViewPort = true
webView.requestFocus(View.FOCUS_DOWN)
webView.clearCache(true)
webView.clearHistory()
webView.webViewClient = object : WebViewClient() {
override fun onPageFinished(webView: WebView?, url: String) {
super.onPageFinished(webView, url)
if (firstTime) {
firstTime = false
webView?.loadUrl(JAVA_SCRIPT)
}
}
}
webView.loadUrl(url)
}
}
Androidmanifest:
<uses-permission android:name="android.permission.INTERNET" />
到目前为止,我一直受困,无法找到解决方案。我使用过processHTML方法来验证HTML是否通过,并且我使用的是布尔值,它不会一直触发同一页面。