2013年8月4日 星期日

a new way to call a JS function from external JS files

The old way is that I create a basic html file containing local javascript code and load it using WebView.loadURL(). In order to call a JS function within an external JS file, I then set up a event handler as onPageFinished() for the WebView Client and call loadURL() which runs a piece of javascript code that include external JS files and call the JS function inside onload attribute of the script tag. However with this method I sometimes can not call the JS functions I need possibly because of the external JS files don't really loaded as I expect whether sequentially or completely, and local JS code does not seem to load at the right time when external JS file inclusion exists.

So now here is the new solution for this after a great deal of experiments.
(1) a very simple html file
(2) a local JS file seperate from the old html file
(3) Use loadDataWithBaseURL() insead of loadURL(). Load data which is the content of the simple html file with modification of adding desired external JS file inclusion and local JS file inclusion
(4) Set up onPageFinished event which only calls the JS function

The code:

        myWebView = new WebView(this);
        myWebView.getSettings().setJavaScriptEnabled(true);
        myWebView.getSettings().setBuiltInZoomControls(true);
        myWebView.getSettings().setUserAgentString("iTunes-AppleTV/5.1 (3; 8GB; dt:12)");
        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:atv.onAppEntry();");
            }
        });
        myWebView.addJavascriptInterface(new MyAndroidJSInterface(this, MainActivity.class), "gtkTV");
        myWebView.loadDataWithBaseURL("file:///android_asset/", new commonUtility(this).addJSsrc2DOM("tmp.html", js_url),"text/html", null, null);


what's not to achieve the goal:
1. Use loadData() instead of loadDataWithBaseURL().
2. Mix inline script code with external JS files inclusion even in the order of correct dependencies.

Reference links
http://stackoverflow.com/questions/3961589/android-webview-and-loaddata
http://developer.android.com/reference/android/webkit/WebView.html
http://developer.android.com/reference/android/webkit/WebViewClient.html#onPageStarted%28android.webkit.WebView,%20java.lang.String,%20android.graphics.Bitmap%29

沒有留言:

張貼留言