agenttom
agenttom

Reputation: 161

Android custom WebView is failing to find javascript functions defined in loaded HTML

I have an Android WebView. I pass HTML to it (as a String). This HTML contains some basic javascript.

Upon load, the HTML attempts to call a javascript function (defined in the <head></head>). This works fine in my browser desktop so I'm sure the HTML/Javascript itself is fine, but it fails to work when I load the same HTML into my WebView.

Here is how I instantiate the WebView:

WebView view = new WebView(context);
WebSettings settings = view.getSettings();
settings.setJavaScriptEnabled(true);
settings.setJavaScriptCanOpenWindowsAutomatically(false);
view.setWebChromeClient(new CustomWebChromeClient());
view.setWebViewClient(new CustomWebViewClient());
view.loadData(ARBITRARY_HTML, "text/html", "utf-8");

The loaded HTML is:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>My head hurts from head-desking</title>
    <style type="text/css">
    #content
    {
        display: none;
    }
    </style>
    <script type="text/javascript">
    //<!--
    function ShowContent()
    {
        document.getElementById('content').style.display = 'block';
    }
    //-->
    </script>
</head>
<body onload="ShowContent()">
    <div id="content">
    This content should be shown, but isn't!
    </div>
    <div id="other">
    All I see is this content... and that makes me question my self worth.
    </div>
</body>
</html>

This produces (on Android only) the runtime javascript error: "Uncaught ReferenceError: ShowContent is not defined".

Upvotes: 4

Views: 2874

Answers (1)

Knickedi
Knickedi

Reputation: 8787

I have an assumption. The //<!-- ... //--> technique which is a made up hack for really old browsers is so out of date. Try to remove that.

Upvotes: 5

Related Questions