Reputation: 390
So I tried to get the value of an input type into a string in my android webview. But I couldnt find a way. Below is my code in the html.
<input class="input100" type="hidden" id="captcha1" name="captcha1" value="<?php echo $_SESSION['captcha']; ?>">
And i wanted to get the value and store it into a string in my android webview. Any clue??
Upvotes: 1
Views: 3501
Reputation: 964
You can use something similar in your code, The function from javascript must return the value and then it will be caught here as follows:
override fun onCreate(savedInstanceState: Bundle?) {
// webView referenced from layout id
webView.settings.javaScriptEnabled = true
webView.webViewClient = MyWebViewClient()
webView.setWebChromeClient(MyWebChromeClient())
webView.loadUrl("http://foobar.com")
}
private class MyWebViewClient : WebViewClient() {
override fun onPageFinished(view: WebView, url: String) {
//functionToReturnSomething() should be \ same as you mention in javascript
view.loadUrl("javascript:alert(functionToReturnSomething())")
}
override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
return false
}
}
private class MyWebChromeClient : WebChromeClient() {
override fun onJsAlert(view: WebView, url: String, message: String, result: JsResult): Boolean {
result.confirm()
return true
}
}
Upvotes: 0
Reputation: 289
You have to register javascript interface to webview. You can add methods with annotaion @JavascriptInterface to android webview controller that can be called from Webview controll. Also don't forgate to remove those from proguard... for more info How to get return value from javascript in WebView of Android? This example will read from html text and put in android text view. You should be always carefullwhile exposing android method to webview java script
import android.content.Context
import android.util.Log
import android.webkit.JavascriptInterface
import android.webkit.WebView
import android.widget.TextView
class MyWebView(context:Context, textView: TextView) {
var outValue:String =""
val myWebView = WebView(context)
val html: String by lazy{"<!DOCTYPE html><head><title>Loading...</title></head><body>"+
"<input type=\"text\" id=\"captcha1\" name=\"captcha1\" onkeyup=\"fromAndroid.getData(value);\">"+
"<img src= /></body></html>"}
init {
val javaScriptInterface = object: JavaScriptInterface{
@JavascriptInterface
override fun getData(data: String){
outValue = data
textView.text = data
Log.d(TAG, data)
}
}
myWebView.settings.setJavaScriptEnabled(true)
myWebView.addJavascriptInterface(javaScriptInterface, "fromAndroid")
myWebView.loadDataWithBaseURL("", html, "text/html","UTF-8", null);
}
companion object{
const val TAG = "MyWebView"
}
}
interface JavaScriptInterface{
fun getData(data: String)
}
Upvotes: 1