Android webview 加载 html,然后设置变量,然后加载脚本

Android webview load html, then set variable, then load script

我的资产文件夹中有这个 html。

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<script type="text/javascript">
        var publicKey = ""

        function setPublicKey(key) {
            publicKey = key;

            var url = '<' + 'script src="https://<my_url>?onload=loadChallenge" async defer>' + '<' + '/script>'
            document.write(url);
        }

        function loadChallenge() {
            //do some stuff using the publicKey
            new Thing( {public_key: publicKey } )
        }
     </script>
<div id="CAPTCHA"></div>
</body>
</html>

我需要将它加载到 webview 中,传递并设置 publicKey,然后在 url.

中加载使用 onLoad 参数的脚本

所以我正在将 html 加载到 webview 中并使用此 WebViewClient:

private val myWebViewClient = object : WebViewClient() {
        override fun onPageFinished(view: WebView?, url: String?) {
            view?.loadUrl("javascript:setPublicKey($publicKey)")
        }
    }

document.write(url) 无效。 document.write("anything") 不工作。

我不喜欢这个解决方案,我只需要一个让我加载 html,然后设置 publicKey,然后加载该脚本的解决方案。

如有任何帮助,我们将不胜感激。

我用这个脚本标签解决了它:

<script type="text/javascript">
    var publicKey = ""

    function setPublicKey(key) {
        publicKey = key;
        console.log("public key: " + publicKey);
        var url = "<my_url>?onload=loadChallenge"
        var s = document.createElement('script');
        s.setAttribute('src', url);
        s.async = true;
        document.body.appendChild(s);
    }

    function loadChallenge() {
        //do some stuff using the publicKey
        new Thing( {public_key: publicKey } )
    }
 </script>

首先,我从文件中将 html 加载到 Web 视图中。

网络视图正在使用此 WebViewClient:

private val myWebViewClient = object : WebViewClient() {
    override fun onPageFinished(view: WebView?, url: String?) {
        view?.loadUrl("javascript:setPublicKey(`$publicKey`)")
    }
}

这会等待 html 加载并调用 setPublicKey() 来设置密钥并加载脚本。

很有魅力。