Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

addJavascriptInterface function doesn't work on API 21

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)

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;
    }
});

My interface:

public class ImpressionSyncJsInterface {
    private final Context context;

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

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

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);
    }
});
like image 426
Daniel Avatar asked Jan 24 '16 16:01

Daniel


1 Answers

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

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

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

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

like image 62
Daniel Avatar answered Sep 28 '22 08:09

Daniel