我的资产文件夹中有这个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>
我需要将其加载到Web视图中,传递并设置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,然后加载该脚本的解决方案。
任何帮助将不胜感激。
答案 0 :(得分:0)
我用以下脚本标签解决了它:
<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文件从文件中加载html。
Web视图正在使用此WebViewClient:
private val myWebViewClient = object : WebViewClient() {
override fun onPageFinished(view: WebView?, url: String?) {
view?.loadUrl("javascript:setPublicKey(`$publicKey`)")
}
}
这将等待html加载并调用setPublicKey()
来设置密钥并加载脚本。
像魅力一样工作。