Search code examples
javascriptandroidwebviewandroid-webviewrecaptcha

How to add a JavaScript function in WebView and call it later from HTML upon submitting reCAPTCHA


I am adding a JavaScript function in WebView like this (Kotlin):

val webView = findViewById(R.id.webview) as WebView
webView.getSettings().setJavaScriptEnabled(true)
webView.addJavascriptInterface(this, "android")
webView.getSettings().setBuiltInZoomControls(false)
webView.loadUrl(url)

webView.webViewClient = object : WebViewClient() {
    override fun onPageFinished(view: WebView, url: String) {
        super.onPageFinished(view, url)
        webView.loadUrl("javascript:(function captchaResponse (token){" +
                        "      android.reCaptchaCallbackInAndroid(token);" +
                        "    })()")
    }
}

The function works fine, but the problem is that it runs immediately, when I add it in WebView. I only want to include it as a JavaScript function and it should be called only from the HTML, when the user will fill the reCAPTCHA. How can I do that?


Solution

  • Try injecting the script like this,

    function addCode(code){
    var addedScript= document.createElement('script');
    addedScript.text= code;
    document.body.appendChild(addedScript);}
    

    now call the function like,

    val codeToExec = "function captchaResponse (token){" +
                        "android.reCaptchaCallbackInAndroid(token);" +
                        "}";
    

    now exec loadurl like,

    webview.loadUrl("javascript:(function addCode(code){
    var addedScript= document.createElement('script');
    addedScript.text= code;
    document.body.appendChild(addedScript);})(codeToExec));