【问题标题】:Uncaught ReferenceError: function is not defined when trying to access in Android webview未捕获的ReferenceError:尝试在Android webview中访问时未定义函数
【发布时间】:2012-08-22 06:14:33
【问题描述】:

我在 Android 中使用 WebView。我正在使用 loadDataWithBaseURL 来加载下面的 url:

(出于安全原因,这里我使用“XXXX”替换我的实际网页网址)

wb.loadDataWithBaseURL("http://XXXX.html", formattedHTML, "text/html", "UTF-8", null);

formattedHTML 的内容包含由我的服务类填充的实际 html 源代码。

http://XXXX.html的完整源码如下:

<html>
    <head>

        <script language="javascript">
            function displayAlert()
            {
                alert("this is in function displayAlert()");
            }
        </script>
    </head>
    <body onload="displayAlert();">dummy
    </body>
</html>

我有一个按钮。单击它时,我希望执行 javascript 函数“displayAlert”: wb.loadUrl("javascript:displayAlert()");

我的问题:

  1. 我在 logCat 视图中遇到此错误消息:Uncaught SyntaxError: Unexpected identifier at http://XXXX.html:1

我搜索了很多网页,其中大多数都说这是由于 javascript 中的“{”和“}”不匹配造成的。但我检查了我的,发现我的 javascript 代码格式正确,如上所示。

  1. 当我单击按钮时,javascript 无法执行。错误消息:E/Web Console(534): Uncaught ReferenceError: displayAlert is not defined at null:1。

我已经通过以下方式在 webview 中启用了 javascript:

WebSettings webSettings = wb.getSettings();
webSettings.setJavaScriptEnabled(true);

为什么“http://XXXX.html”中实现的javascript函数找不到执行?

你能帮帮我吗?非常感谢!

【问题讨论】:

  • 嘿杰里,我已经编辑了我的答案。问候

标签: javascript android webview


【解决方案1】:

使用这个

webView.setWebViewClient(new WebViewClient() {
                @Override
                public void onPageFinished(WebView view, String url)
                {
                    webView.loadUrl("javascript:(function() { " +
                            "alert('hello') " +
                            "})()");
                }
            });

【讨论】:

  • 你是最棒的!!!在挫败了一天之后救了我。今天才知道这个概念......非常感谢
【解决方案2】:

您的问题在于type 属性的写入方式,具有text/javascript 而不是javascript/text 非常重要(type 的顺序必须绝对正确)

    <script type="text/javascript">
        function displayAlert()
        {
            alert("this is in function displayAlert()");
        }
    </script>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-22
    • 1970-01-01
    相关资源
    最近更新 更多