1

I know this question has been asked many times and I have checked all the solutions and researched everything. However, this is simply not working for me.

I don't know what I am doing wrong. Can someone please help me out?

I am loading a local html file in my WebView and then calling the JavaScript function:

wv.loadUrl("file:///android_asset/sample.html");
wv.getSettings().setJavaScriptEnabled(true);
JavascriptInterface javasriptInterface = new JavascriptInterface(MyActivity.this);
wv.addJavascriptInterface(javasriptInterface, "MyInterface");
wv.loadUrl("javascript:loadpath()");

The HTML file is:

<html>
<head>
</head>

<body>
<script type="text/javascript">
    function callDoSomething() {
        // Do something
    }

    function loadpath() {
        // Is not called no matter whatever operation I do here. Just printing a string, setting variable, android callback anything.
        document.write("Hi");
        document.getElementById('img').src = "path.png";
    }
</script>

<form name="myForm" action="FORM">
    <img src=""  alt="Autofill" /><br>
    <input type="button" value="Submit" onClick="callDoSomething()" />
</form>

</body>
</html>
Rachit
  • 5,021
  • 2
  • 14
  • 9

1 Answers1

6

loadUrl() is asynchronous. You are calling your second loadUrl() way too soon. You need to wait until your page is loaded, perhaps by using a WebViewClient and watching for onPageFinished().

CommonsWare
  • 910,778
  • 176
  • 2,215
  • 2,253
  • Oh! Thanks for that info.. Actually my requirement is to pass a parameter to the HTML page. At first I tried out string queries in the first loadUrl path. However, it was giving a web page not found error and after searching found this method. Anyways, I will try implementing onPageFinished() with a WebViewClient. Thanks a lot! – Rachit Mar 07 '13 at 20:58
  • @Rachit: Yes, you cannot use query parameters on local paths, only Web URLs. However, bear in mind that your JavaScript code can call back into your app to retrieve this data, via methods you expose on `JavascriptInterface` and that your script retrieves via calls on `MyInterface`. You do not need to call `loadUrl()` a second time -- have the script *pull* the data, rather than you pushing the data. – CommonsWare Mar 07 '13 at 21:01
  • Yes I hadn't thought of that. But performance wise, which method would be faster? Either of them should be ok for a single paramter. However, if I have to exchange multiple paramaters at different times, is there a trade-off? – Rachit Mar 07 '13 at 21:08
  • @RachitL: "However, if I have to exchange multiple paramaters at different times, is there a trade-off?" -- you are welcome to use both techniques. For example, this sample project shows both pushing a location via `loadUrl("javascript:...")` and pulling a location: https://github.com/commonsguy/cw-omnibus/tree/master/WebKit/GeoWeb2 – CommonsWare Mar 07 '13 at 21:54