未捕获的ReferenceError,通过android应用程序调用javascript函数..?

Amr*_*ngh 5 javascript android webview referenceerror

我试图通过android Webview Activity调用javascript函数setGameName(),但它正在抛出uncaught ReferenceError:setGameName not defined at :1.

我的源代码如下:

webView2.setWebChromeClient(new WebChromeClient());
webView2.getSettings().setLightTouchEnabled(true);
webView2.getSettings().setJavaScriptEnabled(true);
webView2.addJavascriptInterface(jsInterface, "AndroidFunction");
webView2.loadUrl("file:///android_asset/www/index.html");
webView2.loadUrl("javascript:setGameName()");
Run Code Online (Sandbox Code Playgroud)

Html代码:

    <body>

        <script type="text/javascript">
            function init() {
                console.log("====== I am getting called::===");
                var testVal = document.getElementById('playertextId').value;
                AndroidFunction.proceedFurther(testVal);
            };

            function setGameName() {
                console.log("====== Got the value===");
                document.getElementById('gametextId').value;
            };
        </script>
</body>
Run Code Online (Sandbox Code Playgroud)

它正在加载index.html很好但在函数调用时抛出异常,请提供适当的解决方案..

更新:

i have found the problem the page is not getting loaded at the time of function call..(Since on giving a time delay of 5000ms it is getting called..)!!
Run Code Online (Sandbox Code Playgroud)

但是我如何实施呢?

a b*_*ver 5

loadUrl是异步的。这意味着它会在页面加载之前立即返回。因此,当您尝试调用setGameName时尚不存在。

您可以使用onPageFinished方法实现WebClient并在其中调用您的JavaScript代码。

  • [here](http://lexandera.com/2009/01/injecting-javascript-into-a-webview/)是一个很好的例子。 (2认同)