TAGS :Viewed: 11 - Published at: a few seconds ago

[ 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:


        <script language="javascript">
            function displayAlert()
                alert("this is in function displayAlert()");
    <body onload="displayAlert();">dummy

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();

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

Would you please kindly help me? Thanks a lot!

Answer 1

use this

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

Answer 2

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()");