return 在 onPageFinished 之前调用

return called before onPageFinished

我有一个 WebView 用于一些简单的网络抓取,它工作正常但是当我把它放在一个函数中并尝试 return 它抓取的任何内容时 return 部分在WebView 甚至被刮掉了。我怎样才能让它在调用 return 之前等待,因为不可能在 onPageFinished 中使用 return?

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
    }

onPageFinished() 是一个回调,它被异步调用(每当页面加载时) 你的函数 returns.

之后

你不应该在函数中有这个回调。而是在 onCreate() 中进行配置,设置回调并传递 resultString,一旦它可用,无论您需要它:

  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
                }
            }
    }
  }