简体   繁体   中英

How can I pass data to Javascript in a WebView using a Javascript interface in Java code?

I am trying to pass a variable from my Android Java code to Javascript in a WebView using a Javascript Interface, but the alert says "undefined".

This is part of the Java:

public class WebAppInterface {
    Context mContext;

    WebAppInterface(Context c) {
        mContext = c;
    }

    @JavascriptInterface
    public int getValue() {
        return 5;
    }
 }

And the Javascript:

function getValue() {
    Android.getValue();
}

var value = getValue();
alert(value);

Note that my Interface is called "Android". What am I doing wrong?

Try adding the 'return' keyword to your getValue function:

function getValue() {
  return Android.getValue();
}

alert(getValue());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM