Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncaught ReferenceError: function is not defined when trying to access in Android webview

I am using WebView in Android. I am using loadDataWithBaseURL to load url below:

( here I use "XXXX" to replace my actual webpage URL for security reason )

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

The content of formattedHTML contains the actual html source code populated by my service class.

the complete source code of http://XXXX.html is below:

<html>
    <head>

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

And I have a button. When it is clicked, I would like to have the javascript function "displayAlert" executed: wb.loadUrl("javascript:displayAlert()");

My problem:

  1. I meet with this error message in logCat view: Uncaught SyntaxError: Unexpected identifier at http://XXXX.html:1.

I searched quite a lot web pages and most of them said this is caused by the unmatch "{" and "}" in the javascript. But I checked mine and found my javascript code has correct format, as you see above.

  1. When I click the button, the javascript is failed to be executed. Error message: E/Web Console(534): Uncaught ReferenceError: displayAlert is not defined at null:1.

I have already enabled javascript in webview via:

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

Why the javascript function implemented in "http://XXXX.html" cannot be located for execution?

Would you please kindly help me? Thanks a lot!

like image 778
user1615981 Avatar asked May 25 '26 05:05

user1615981


2 Answers

use this

webView.setWebViewClient(new WebViewClient() {
                @Override
                public void onPageFinished(WebView view, String url)
                {
                    webView.loadUrl("javascript:(function() { " +
                            "alert('hello') " +
                            "})()");
                }
            });
like image 173
kevinl Avatar answered May 27 '26 17:05

kevinl


Your problem is with the way your type attribute is written, having text/javascript and not javascript/text is very important (the ordering of the type has to be absolutely correct)

    <script type="text/javascript">
        function displayAlert()
        {
            alert("this is in function displayAlert()");
        }
    </script>
like image 41
classicjonesynz Avatar answered May 27 '26 17:05

classicjonesynz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!