我有返回值的JS
function sendDisplay()
{
var dis = alert(reader.dom.find('controls_contents_container').style.display);
return dis;
}
在 android 中,我尝试设置返回值,以便我可以在 android 中创建 if else 语句
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())");
}
}
当我在 loadUrl 方法中发出警报时,它显示来自 JS 的值。但我不知道如何将该值设置为 android 变量。
TQ
最佳答案
查看关于 Binding Javascript Code to Android Code 的 Google 指南部分。我还将在这里发布一个简短的摘要:
您首先需要设置一个 Java 类:
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();
}
}
然后,您需要将该类的实例作为 JavaScript 接口(interface)添加到您的 WebView:
WebView webView = (WebView) findViewById(R.id.webview);
webView.addJavascriptInterface(new JavaScriptInterface(this), "Android");
最后,您可以使用 javascript 中的“Android.showToast(whatever)”来调用它,也可以从 Java 代码中调用该 javascript:
loadUrl("javascript:Android.showToast(whatever)");
在显示 Toast 消息的情况下,这有点多余。但希望您能明白。
关于javascript - 如何从javascript返回值在android中设置变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13292885/