addJavascriptInterface 函数在 API 21 上不起作用 [英] addJavascriptInterface function doesn't work on API 21

查看:223
本文介绍了addJavascriptInterface 函数在 API 21 上不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试向我找到的 WebView 添加一个 javascript 界面.我遵循了所有标准教程,但仍然在努力完成任务.添加javascript接口时,没有出现任何异常或错误,但是从JS显式调用桥接时,出现以下错误:

I'm trying to add a javascript interface to a WebView I've found. I followed all the standard tutorial and still getting struggled with the task. When adding the javascript interface, I don't get any exceptions or errors, but when explicitly calling the bridge from JS, I get the following error:

I/chromium: [INFO:CONSOLE(1)] "Uncaught ReferenceError: JSNativeBridge is not defined", source:  (1)

添加javascript接口:

Adding the javascript interface:

new Handler(context.getMainLooper()).post(new Runnable() {
    @Override
    public void run() {
        WebView webView = webViews[0];
        if (Constants.DEBUG_MODE) {
            webView.setWebChromeClient(new WebChromeClient());
            webView.getSettings().setJavaScriptEnabled(true);
        }
        ImpressionSyncJsInterface impressionSyncJsInterface = new ImpressionSyncJsInterface(context);
        webView.addJavascriptInterface(impressionSyncJsInterface, JS_BRIDGE_NAME);
        didAddInterfaceToWebView = true;
    }
});

我的界面:

public class ImpressionSyncJsInterface {
    private final Context context;

    public ImpressionSyncJsInterface(Context context) {
        this.context = context;
    }

    @JavascriptInterface
    public void foo() {
        Log.e("TEST", "test");
    }
}

Javascript 执行:

The Javascript execution:

final String javascriptInjectionTest = "javascript: " + JS_BRIDGE_NAME + ".foo();";

new Handler(Looper.getMainLooper()).post(new Runnable() {
    @Override
    public void run() {
        webView.loadUrl(javascriptInjectionTest);
    }
});

推荐答案

找出问题所在,所以我将分享我的见解:

Figured out the problem, so I'll share my insights:

addJavascriptInterface 函数仅适用于 BEFORE loadUrl/loadData 函数.

The addJavascriptInterface function applies only if called BEFORE a loadUrl / loadData function.

就我而言 - 我希望 addJavascriptInterface 注入一个 JS 桥接器,但我从未重新加载 WebView 内容,因此它从未被主动注入.

In my case - I expected addJavascriptInterface to inject a JS bridge, but I never reloaded the WebView content, so it was never actively injected.

重新加载 WebView HTML 内容后,网桥已按预期添加.

After reloading the WebView HTML content, the bridge was added as expected.

这篇关于addJavascriptInterface 函数在 API 21 上不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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