如何获取android webViewClient的原始HTML响应

时间:2018-10-28 21:35:57

标签: android android-webview webviewclient

  • 解决方案必须适用于API> 20
  • This solution does not work。我认为它仅适用于较低版本的Android API。我正在Android 8.0上进行测试。
  • 我已经尝试在页面加载后立即使用Retrofit,而不是通过WebViewClient获取html。但是用户未登录改造请求。然后我两次执行相同的请求。

    @SuppressLint("JavascriptInterface")
    private fun initializeWebView(url : String?) {
        binding.webView.loadUrl(url)
        binding.webView.settings.javaScriptEnabled = true
        binding.webView.settings.useWideViewPort = true
        binding.webView.requestFocus(View.FOCUS_DOWN)
        binding.webView.addJavascriptInterface(MyJavaScriptInterface(context!!), "HtmlViewer");
    
        binding.webView.webViewClient = object : WebViewClient() {
            override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean {
                return false
            }
    
            override fun onPageFinished(view: WebView?, url: String?) {
    //              super.onPageFinished(view, url)
    
            //tried adding a sleep, but doesn't work:
            Thread.sleep(6000)
    
                   //showHTML method is not being called:                
     binding.webView.loadUrl("javascript:window.HtmlViewer.showHTML" +
                        "('<html>'+document.getElementsByTagName('html')[0].innerHTML+'</html>');")
    
     // Prints out: html: null
                binding.webView.evaluateJavascript(
                        "javascript:window.HtmlViewer.showHTML" +
                                "('<html>'+document.getElementsByTagName('html')[0].innerHTML+'</html>');"
                ) { html ->
                    Log.d("HTML", html)
                    // code here
                }
            }
        }
    }
    
    
    class MyJavaScriptInterface(val context: Context) {
    
      fun showHTML(html: String) {
        Log.d("",""+html)
    
        AlertDialog.Builder(context).setTitle("HTML").setMessage(html)
          .setPositiveButton(android.R.string.ok, null).setCancelable(false).create().show()  }
    }
    

0 个答案:

没有答案