Katana24
Katana24

Reputation: 8959

Webview & Javascript Relationship

I've been looking about for a proper explanation about javascript's relationship with the android WebView. Can anyone tell me: if I an HTML page online and all the required javascript files to make what I need work on that HTML page, can I port it to android.

For example could I move the javascript files onto the android app local folder ( if so: which folder? ) and call a function from in the app. Then could I get the result of the javascript function from one of those files?

If anyone has any tutorials or resources related to this could you point me in the right direction?

Upvotes: 0

Views: 161

Answers (1)

jsaye
jsaye

Reputation: 914

When you have a WebView you can set a Webchormeclient or a Webviewclient, the webchromeclient will be similar to your chrome desktop browser. The other option is to use a Webviewclient this webview client can be configurated as you wish, you can add an "interface" to call Javascript functions from your java code, or java functions from your Javascript code. The interface is a class and can be something like this: final class JavaScriptInterface {

        public void myalert(String message){
            new AlertDialog.Builder(wview.getContext()).setMessage(message).setNeutralButton("Ok",new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    dialog.cancel();
                }
            }).show();

        }

The webview has a method to "attach" this class to the Javascript:

wview.addJavascriptInterface(new JavaScriptInterface(), "interface);

Once you have add the JavascriptInterface, you can call the method myalert("hi") from the Javascript code, to do so, you will have to do something like:

window.interface.myalert("hi") //This is called in the Javascript

if you want to call a Javascript from the Java code you can do something like this:

wview.loadUrl("javascript:changeValues('"+name+"','"+id+"')");//this will call a Javascript function called changeValues, and will pass to variables (name, id)

To sum up, the webchromeclient is easier to use but the webviewclient allows you more configuration. Before, maybe you want to read about phonegap which is a framework to devlop Webapps x-platform. Hope you that this fast explanation helps you a little.

PS: With the second option you can store all that you need in the sdcard.

Upvotes: 1

Related Questions