JavaScriptInterface未调用

时间:2012-02-06 20:13:06

标签: javascript android

为什么我的代码不会触发我的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");

    }
}

package 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();
    }

}

1 个答案:

答案 0 :(得分:1)

只是一个猜测,但值得一试,因为我没有看到任何其他明显错误。改变这个:

    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>";