【问题标题】:uncaught ReferenceError,Calling javascript function through android application..?未捕获的 ReferenceError,通过 android 应用程序调用 javascript 函数..?
【发布时间】:2013-02-26 10:13:37
【问题描述】:

我正在尝试通过 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()");

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>

它加载 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..)!!

但是我该如何实现它呢..?

【问题讨论】:

    标签: javascript android webview referenceerror


    【解决方案1】:

    我不太确定,但可能您需要将 file:///android_asset/www/index.html 放在网络服务器上,然后检索它。默认情况下,浏览器不允许 JS 从来自 Filesystems 的 JS 加载。

    【讨论】:

    • @gashu...不是这样..文件正在加载并且内部javascript函数工作正常。只是从活动到 js 的调用正在引发异常..
    【解决方案2】:

    loadUrl 是异步的。这意味着它在页面加载之前立即返回。所以当你尝试调用它时,setGameName 还不存在。

    您可以使用 onPageFinished 方法实现 WebClient 并在那里调用您的 javascript 代码。

    【讨论】:

    • @ZerflagL..能否请您详细说明我应该如何实现它..?
    • here 就是很好的例子。
    猜你喜欢
    • 1970-01-01
    • 2017-11-08
    • 1970-01-01
    • 2013-10-09
    • 1970-01-01
    • 1970-01-01
    • 2017-01-17
    • 2021-01-27
    • 1970-01-01
    相关资源
    最近更新 更多