0

I need to get some properties of an html page which is loaded in a webview. Something similar to what is here: stringByEvaluatingJavascriptFromString (iOS method, what is Android equivalent?)

So I have a JavaScriptInterface:

class MyJavaScriptInterface {
    @android.webkit.JavascriptInterface
    public void jsCallback(String jsResult) {
        // your code...
        Log.d("Debug", jsResult);
    }
}

ant then here is the JS I use to get the string I need:

webView.addJavascriptInterface(new MyJavaScriptInterface(), "HTMLOUT");
    webView.loadUrl("javascript:( "
            + "function () { "
            + "var htmltag = document.getElementsByTagName(\"html\");"
            + "var dataStr = htmltag[0].getAttribute(\"some-data-property-i-need\"); "
            + "console.log(window.HTMLOUT);"
            + "window.HTMLOUT.jsCallback(dataStr); } ) ()");

now in the console I see this traces:

06-02 01:14:06.409: V/CallNative fired:(26789): objc://domReady
06-02 01:14:06.464: I/Web Console(26789): undefined at null:1
06-02 01:14:06.480: E/Web Console(26789): Uncaught TypeError: Cannot call method 'jsCallback' of undefined at null:1

and I have no idea why "window.HTMLOUT" is undefined. Please note that it was working at a point and then I modified a bit the JS part but I still cannot figure it out what could be the problem.

Community
  • 1
  • 1
Ciprian
  • 2,879
  • 3
  • 28
  • 28

1 Answers1

0

JS code can be executed after the whole page is loaded, have a try at this way:

webView.setWebViewClient(new WebViewClient() {
    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);
        // Call JS code here
    }
});
webView.loadDataWithBaseURL(null, "<html></html>", "text/html", "UTF-8", "");

If previous method does not work, please have a try at HTMLOUT.jsCallback(dataStr) instead of window.HTMLOUT.jsCallback(dataStr).

Davidsun
  • 721
  • 6
  • 13
  • I tried... same problem... well a bit different: 06-02 01:45:01.847: E/Web Console(325): Uncaught ReferenceError: HTMLOUT is not defined at null:1 – Ciprian Jun 01 '13 at 23:45
  • @Ciprian I've modified my answer. – Davidsun Jun 02 '13 at 00:21
  • Hi, sorry for the late reply, I tried that thing and it is the same, I can't get it working. But I've noticed that if I call something like this: webView.addJavascriptInterface(new MyJavaScriptInterface(), "HTMLOUT"); webView.loadUrl("javascript:( " + "function () { })()"); after the loadUrl of the page I want I get the stuff. But I still don't understand why... – Ciprian Jun 05 '13 at 08:20