JavaScript接口无法查找功能 [英] JavaScript Interface Cannot Find Function

查看:120
本文介绍了JavaScript接口无法查找功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 JavaScriptInterface 类,它只有一个函数。该函数使用 @JavascriptInterface 进行注释,我相信我已经正确设置了它。

I have a JavaScriptInterface class that has a single function. The function is annotated with @JavascriptInterface and I believe I have set it up correctly.

public class JavaScriptInterface {

    ...

    @JavascriptInterface
    public void processBody(String uri, String body) {
        Log.d(TAG, "Process body");
        ...
    }
}

然后我设置JavaScriptEnabled在 WebView 上并尝试调用该函数:

Then I set JavaScriptEnabled on the WebView and attempt to call the function:

final WebView webView = new WebView(this);
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(new JavaScriptInterface(), "java");

webView.setWebViewClient(new WebViewClient() {
    @Override
    public void onPageFinished(WebView view, String url) {
        Log.d(TAG, "Page finished");
        callJavaScript();
    }
});

页面完成加载,然后我尝试了各种方法从我的<调用JavaScript函数code> JavaScriptInterface 。使用以下两种方法之一:

The page finishes loading, then I have tried a variety of methods to call the JavaScript function from my JavaScriptInterface. Using one of these two methods:

view.evaluateJavascript(javascript);

view.loadUrl("javascript:" + javascript);

以及其中一个javascript字符串:

And one of these javascript strings:

"(function() { window.java.processBody('" + url + "', document.body.innerHTML); })()"

"(function() { processBody('" + url + "', document.body.innerHTML); })()"

"window.java.processBody('" + url + "', document.body.innerHTML);"

"processBody('" + url + "', document.body.innerHTML);"

每次收到错误消息时:

I/chromium: [INFO:CONSOLE(1)] "Uncaught TypeError: processBody is not a function", source: (1)

虽然在较旧的设备(前KitKat)上错误消息从未显示,但该功能永远不会被调用。

Though on older devices (pre KitKat) the error message never shows up, the function just never gets called.

此方法以前也一直在使用,我不相信我已经更改了此活动的任何代码。今天早上我刚刚意识到了这个错误。

This method also had been working previously, and I do not believe I have changed any of the code for this activity. I was just made aware of the bug this morning.

推荐答案

正如我们与布莱恩一样,这个问题是由ProGuard引起的剥离未从Java调用的函数。一个快速而简单的测试是在Java中添加一些调用JS接口函数的代码,看看它是否有帮助。

As we have figured out with Bryan, the problem was due to ProGuard stripping out functions that are not called from Java. A quick and simple test is to add some code in Java that calls the JS interface function, and see whether it helps.

有关如何配置ProGuard不剥离的信息注入Java对象的方法,请参阅如何为javascript界面​​配置proguard?

For information on how to configure ProGuard not to strip out methods of injected Java objects, see How to configure proguard for javascript interface?

这篇关于JavaScript接口无法查找功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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