【问题标题】:Android javascript interface in webviewwebview中的Android javascript界面
【发布时间】:2015-02-18 13:30:57
【问题描述】:

我正在尝试将 javascript 界面与 google maps javascript 库一起使用。
我进行了搜索,发现了一种几乎与此 JavascriptInterface 相似的方法。

这是我的代码:

 <script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>

 <script type="text/javascript">
    function testAPI() {
        JSInterface.test();
    }
 </script>
 <script>
  // gooogle maps code 
  // 
 </script>
 </head>
 <body>
 <div id="map-canvas"></div>
 <div><input type="button" value="Make Toast" onClick="testAPI()" /></div>

这是我的界面:

public class JavaScriptInterface {
private Activity activity;

public JavaScriptInterface(Activity activiy) {
    this.activity = activiy;
}

public void test(){
    Toast.makeText(activity.getApplicationContext(),
            "Javascript interface test.", 0).show();
}
}

这是我创造一切的地方:

myBrowser = (WebView) findViewById(R.id.mybrowser);

    myBrowser.setWebChromeClient(new WebChromeClient() {
        public void onGeolocationPermissionsShowPrompt(String origin,
                GeolocationPermissions.Callback callback) {
            callback.invoke(origin, true, false);
        }
    });
    myBrowser.getSettings().setJavaScriptEnabled(true);
    String javascrips = null;
    // myBrowser.loadUrl("file:///android_asset/geolocation.html");
    try {
        AssetManager am = getAssets();
        InputStream input = am.open("geolocation.html");
        int size;
        size = input.available();
        byte[] buffer = new byte[size];
        input.read(buffer);
        input.close();
        javascrips = new String(buffer);
    } catch (IOException e) {
        e.printStackTrace();
    }
    jsInterface = new JavaScriptInterface(this);
    myBrowser.addJavascriptInterface(jsInterface, "JSInterface");

    myBrowser.loadDataWithBaseURL("file:///android_res/raw/", javascrips,
            "text/html", "UTF-8", null);

单击按钮时(带有 testAPI() 函数的 javascript 输入),什么也没有发生,为什么 Toast 不显示?

【问题讨论】:

  • 没有 maps api 是否可以工作?
  • 好的,你可能想先解决这个问题。 html 中对testAPI() 的调用是否应该在其后加上分号?我做的 java 比 javaScript 多;)
  • 不,我不这么认为,我也试过了。

标签: javascript android webview interface


【解决方案1】:

尝试将@JavascriptInterface 添加到您的 test() 方法中

http://developer.android.com/reference/android/webkit/JavascriptInterface.html

需要以JellyBean开头的注解

【讨论】:

  • 欢迎,当我们更改默认构建平台时,我难过了一天。
猜你喜欢
  • 1970-01-01
  • 2012-12-11
  • 2011-07-20
  • 2013-02-25
  • 2014-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多