Search code examples
javascriptandroidhtmlkotlinwebview

Android Webview evaluateJavascript returns null


I am trying to get username from webview. It returns null object.

webView.settings.javaScriptEnabled = true

webView.evaluateJavascript(
  "(function() { return  document.getElementsByClassName('lgn-loginname') })();",
  ValueCallback<String> { s ->
  // 's' contains the result of the JavaScript evaluation
  Log.d("JavaScript Result", "Result: $s")
  })

Also with this it is null.

webView.evaluateJavascript(
  "(function() { var elements = document.getElementsByClassName('lgn-loginname'); " +
  "return elements.length > 0 ? elements[0].innerHTML })();",
  ValueCallback<String> { s ->
  // 's' contains the result of the JavaScript evaluation
  Log.d("JavaScript Result", "Result: $s")
})

I tried many things and always getting null. What am I doing wrong?


Solution

    • The issue you're facing is because the JavaScript code is being executed before the web page has finished loading. As a result, the elements you're trying to access are not yet available.

    • You need to wait for the page to load completely before executing the JavaScript code. You can do this by using a WebViewClient and overriding its onPageFinished method. Here's how you can do it

      webView.webViewClient = object : WebViewClient() {
        override fun onPageFinished(view: WebView, url: String) {
         super.onPageFinished(view, url)
      
         webView.evaluateJavascript(
           "(function() { var elements = document.getElementsByClassName('lgn-loginname'); " +
           "return elements.length > 0 ? elements[0].innerHTML : null })();",
              ValueCallback<String> { s ->
                 // 's' contains the result of the JavaScript evaluation
                 Log.d("JavaScript Result", "Result: $s")
              }
           )
        }
      }