0

i have JS which return the value

function sendDisplay()
{
 var dis = alert(reader.dom.find('controls_contents_container').style.display);
 return dis;
}

in android i try to set the return value so i can make a if else statement in android

public class MainActivity extends DroidGap {

   @Override
    public void onCreate(Bundle savedInstanceState) {
        CookieManager.setAcceptFileSchemeCookies(true);
        super.onCreate(savedInstanceState);
        super.setIntegerProperty("splashscreen", R.drawable.cover);
        super.loadUrl("file:///android_asset/www/index.html",1500);   

    }


    @Override
    public void onBackPressed() {
        super.loadUrl("javascript:alert(sendDisplay())"); 


    }


}

when i alert in loadUrl method, its show value from JS. but i dont know how to set that value to android variable.

TQ

apsillers
  • 112,806
  • 17
  • 235
  • 239
Mike NOFX
  • 41
  • 1
  • 6
  • To do Java-to-JavaScript communication, I think you'll need to make a [custom PhoneGap plugin](http://docs.phonegap.com/en/2.1.0/guide_plugin-development_index.md.html) that run in JavaScript with an Android back-end [Plugin object](http://docs.phonegap.com/en/2.1.0/guide_plugin-development_android_index.md.html) to catch the message sent from JavaScript. – apsillers Nov 08 '12 at 16:24
  • This is a duplicate of http://stackoverflow.com/questions/3298597/how-to-get-return-value-from-javascript-in-webview-of-android – Keith Feb 11 '13 at 17:02

1 Answers1

2

Take a look at Google's guide section on Binding Javascript Code to Android Code. I'll also post a short summary here:

You'll first need to set up a Java class:

public class JavaScriptInterface {
    Context mContext;

    /** Instantiate the interface and set the context */
    JavaScriptInterface(Context c) {
        mContext = c;
    }

    /** Show a toast from the web page */
    public void showToast(String toast) {
        Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
    }
}

Then, you'll need to add an instance of that class to your WebView as a javascript interface:

WebView webView = (WebView) findViewById(R.id.webview);
webView.addJavascriptInterface(new JavaScriptInterface(this), "Android");

Finally, you can call it using "Android.showToast(whatever)" from javascript, or you can call that javascript from your Java code:

loadUrl("javascript:Android.showToast(whatever)");

Which is a little redundant in the case of showing a Toast message. But hopefully you get the idea.

ajpolt
  • 1,002
  • 6
  • 10