2013年7月28日 星期日

new JS2ANRD interface for javascript-only-semantics coding within a JS file

The JS files provided by the server use custom client interface that is beyond what Android can support, such as function pointer assignment and accessing array using string index. Thus an additional interface has to be included to form the following Android<->Javascript communication:

                                             Client                                             |                Server
local Android interface <---> local custom Javascript interface <---> remote Javascript code
        (gtkTV)                                            (atv)                                     

The following is the sample code:

[local tmp.html]

<HTML>
<head>
<script>
function atvclass() {
    this.loadXML = function(doc) {
        gtkTV.loadXML(doc);
    };
    this.parseXML = function(xml) {
        return gtkTV.parseXML(xml);
    };
    this.sessionStorage = new Array();
}

var atv = new atvclass();
</script>
</head>
<body>
</body>
</HTML>


[executing JS function]
...
       WebView myWebView = new WebView(this);
        myWebView.getSettings().setJavaScriptEnabled(true);
        myWebView.getSettings().setBuiltInZoomControls(true);
        System.out.println(android.os.Build.VERSION.SDK_INT);
        if(android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {
            myWebView.getSettings().setAllowUniversalAccessFromFileURLs(true);
        }
        myWebView.setWebChromeClient(new WebChromeClient());
        myWebView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                view.loadUrl("javascript:(function() { "
                        + " document.getElementByTagName = function(id) {"
                        + "     return document.getElementsByTagName(id);"
                        + " };"
                        + js_url_string
<--composed of creating script nodes to include multiple JS files
                        + "})()");
            }
        });
        myWebView.addJavascriptInterface(new MyAndroidJSInterface(this, SecondActivity.class), "gtkTV");
        myWebView.loadUrl("file:///android_asset/tmp.html");


[sample server JS code]

...
atv.Element.prototype.getElementByTagName = function(name)
    {
        var elements = this.getElementsByTagName(name);
        return(elements && elements.length > 0) ? elements[0] : undefined;
    };

...
atv.sessionStorage['srtlist'] = srtlist;
atv.sessionStorage['filelist'] = filelist;
...

Reference links
http://www.phpied.com/3-ways-to-define-a-javascript-class/

沒有留言:

張貼留言