简体   繁体   中英

Javascript in WebView doesn't work

I am trying the examples from here: https://developer.android.com/guide/webapps/webview.html but it just Doesn't Work™.

This is my Activity :

public class MainActivity extends Activity {
    private static final String TAG = "browser";
    protected WebView wv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        wv = (WebView)findViewById(R.id.wvBrowser);
        WebSettings webSettings = wv.getSettings();
        webSettings.setJavaScriptEnabled(true);
        wv.addJavascriptInterface(new WebAppInterface(this), "android");

        wv.loadUrl("http://192.168.3.183");
    }
} 

This is the WebAppInterface :

public class WebAppInterface {
    Context mContext;

    /** Instantiate the interface and set the context */
    WebAppInterface(Context c) {
        mContext = c;
    }

    /** Show a toast from the web page */
    @JavascriptInterface
    public void showToast(String toast) {
        Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
    }
}

and, finally the Javascript:

<html>
<head>
    <title>Android JavaScript Scan Test</title>
</head>
<body>
<h3>Scan Test</h3>
<input id="barcode">

<input type="button" value="Say hello" onClick="showAndroidToast('Hello Android!')" />

<script type="text/javascript">
    f = 0;
    function showAndroidToast(toast) {
        document.getElementById("barcode").value = typeof(Android) + (f++);

        Android.showToast(toast);
    }
</script>
</body>
</html>

And all it gives me is undefined0 , undefined1 , etc. Apparently, the Android object is not available in my WebView .

Am I missing something?

You registered the callback with android and trying to use it with a capitalized letter Android .

The names need to be identical for Javascript interfaces to work. Currently there is a bug in the Android documentation example

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