Issue
I have a WebView I use for some simple web scraping, which works fine but when I put it in a function and try to return whatever it scraped the return part is called before the WebView even scraped. How can I make it wait before calling return, since a return inside onPageFinished isn't possible?
fun loadText() : String {
myWebView2 = findViewById(R.id.webView2)
var stringToBeReturned = ""
myWebView2.settings.javaScriptEnabled = true
myWebView2.webViewClient = object : WebViewClient() {
override fun onPageFinished(view: WebView, url: String) {
super.onPageFinished(myWebView2, url)
myWebView2.evaluateJavascript("(function() { return ('<html>'+document.getElementsByTagName('html')[0].innerHTML+'</html>'); })();") { value ->
stringToBeReturned = value.substringAfter("on \\u003C/span>\\u003Ca href=\\\"").substringBefore('\\')
}
}
}
myWebView2.loadUrl("https://www.examplewebsite.com")
return stringToBeReturned
}
Solution
onPageFinished()
is a callback, that gets called asynchronously (whenever the page has been loaded) after your function returns.
You should not have this callback in a function. Instead do the configuration in onCreate()
, set the Callback and pass the resultString
, once its available, wherever you need it:
override fun onCreate(savedInstanceState: Bundle?) {
val webView: WebView = findViewById(R.id.webView2)
webView.settings.javaScriptEnabled = true
webView.webViewClient = object : WebViewClient() {
override fun onPageFinished(view: WebView, url: String) {
// this function gets called as soon the page has been loaded
super.onPageFinished(view, url)
webView.evaluateJavascript("(function() { return ('<html>'+document.getElementsByTagName('html')[0].innerHTML+'</html>'); })();") { value ->
val resultString = value.substringAfter("on \\u003C/span>\\u003Ca href=\\\"").substringBefore('\\')
// pass resultString wherever you need it
}
}
}
}
Answered By - ChristianB
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.