[英]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.