[英]JavaScriptInterface not called
为什么下面的代码不会触发我的JavaScriptInterface:当加载Webview时,看不到任何对话框弹出窗口(我想应该是android.widget.Toast)。
package com.example;
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;
public class MyActivity extends Activity
{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String data = "<html>" +
"<body><h1>Test JavaScriptInterface</h1></body>" +
"<script>Android.showToast(toast);</script>" +
"</html>";
WebView engine = (WebView) findViewById(R.id.web_engine);
engine.getSettings().setJavaScriptEnabled(true);
engine.addJavascriptInterface(new JavaScriptInterface(this), "Android");
engine.loadData(data, "text/html", "UTF-8");
}
}
包com.example;
import android.content.Context;
import android.widget.Toast;
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();
}
}
只是一个猜测,但值得一试,因为我没有发现其他明显错误的地方。 更改此:
String data = "<html>" +
"<body><h1>Test JavaScriptInterface</h1></body>" +
"<script>Android.showToast(toast);</script>" +
"</html>";
对此:
String data = "<html>" +
"<body><h1>Test JavaScriptInterface</h1></body>" +
"<script>Android.showToast('toast');</script>" +
"</html>";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.