简体   繁体   中英

JavaScriptInterface not called

Why my code below doesn't trigger my JavaScriptInterface : I can't see any dialogbox popup (I guess that android.widget.Toast is supposed to do) when webview loads.

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

}

Just a guess, but worth a shot since I don't see anything else obviously wrong. Change this:

    String data = "<html>" +
            "<body><h1>Test JavaScriptInterface</h1></body>" +
            "<script>Android.showToast(toast);</script>" +
            "</html>";

to this:

    String data = "<html>" +
            "<body><h1>Test JavaScriptInterface</h1></body>" +
            "<script>Android.showToast('toast');</script>" +
            "</html>";

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