Android 4.2.1、WebView 和 javascript 界面中断 [英] Android 4.2.1, WebView and javascript interface breaks

查看:17
本文介绍了Android 4.2.1、WebView 和 javascript 界面中断的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个添加了 javascript 界面的 webview,它可以在大多数设备上完美运行,除了那些运行 Android 4.2.1 的设备.

I have a webview with added javascript interface which works perfectly on most devices, except for those running Android 4.2.1.

我删除了大部分代码,保留了一个非常基本的代码:

I removed most of the code, and stayed with a very basic code:

this.webView.getSettings().setJavaScriptEnabled(true);
this.webView.setWebChromeClient(new WebChromeClient());
this.webView.addJavascriptInterface(new Object() {
    public void handshake() {
        Log.d("JS", "handshake no params");
    }

    public void handshake(String json) {
        Log.d("JS", "handshake with params: " + json);
    }
}, "Android");

在 javascript 方面,测试代码如下所示:

In the javascript side of things the testing code looks like this:

Android.handshake();

但我在 logcat 中得到了这个:

But I get this in the logcat:

E/Web 控制台:未捕获的类型错误:对象 [对象对象] 没有方法'握手'

E/Web Console: Uncaught TypeError: Object [object Object] has no method 'handshake'

同样,同样的事情在我测试过的具有较旧 android 操作系统(<4.2.1)的设备中也能正常工作(最低版本为 2.3.3).

Again, this same exact thing works fine in devices who are have older android os (< 4.2.1) that I have tested (the minimal version being 2.3.3).

奇怪的是,如果我开始一个全新的项目,只有一个只有 WebView 的 Activity,使用相同的代码,即使对于 4.2.1,一切都可以正常工作,但是当它是我实际项目的一部分时,事情破了.我没有对 webview 做任何事情,我提供的代码片段中没有包含这些内容.

The strange thing is that if I start a completely new project, with nothing but a single Activity which has just a WebView, with the same code, everything works fine even for 4.2.1, but when it's part of my actual project, things break. There's nothing I'm doing with the webview which is not included in this code snippets I provided.

对我来说最奇怪的是 javascript 找到了 Android 对象,但它只是没有请求的方法(握手),这怎么可能?

What is the most strange to me is that the javascript finds the Android object but it just does not have the requested method (handshake), how can that be?

任何帮助将不胜感激,因为这在过去 2 周左右一直让我发疯(这是我一直回到的错误,然后放弃等).谢谢.

Any help will be greatly appreciated since this has been driving me crazy for the past 2 weeks or so (it's a bug I go back to all the time, then give up, etc). Thanks.

推荐答案

来自 Android 4.2 文档:

From the Android 4.2 documentation:

注意:如果您已将 targetSdkVersion 设置为 17 或更高,则必须将 @JavascriptInterface 注释添加到您希望在网页代码中可用的任何方法(该方法也必须是公共的).如果您不提供注释,则在 Android 4.2 或更高版本上运行时,您的网页将无法访问该方法.

Caution: If you've set your targetSdkVersion to 17 or higher, you must add the @JavascriptInterface annotation to any method that you want available your web page code (the method must also be public). If you do not provide the annotation, then the method will not accessible by your web page when running on Android 4.2 or higher.

这篇关于Android 4.2.1、WebView 和 javascript 界面中断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆