Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing appView from Cordova 5.0.0

I'm having real trouble to access appView from the latest Cordova version for Android (5.0.0).

For example, say I want to add a Javascript interface to my app. Before this version, I used to write this line of code:

super.appView.addJavascriptInterface(new WebAppInterface(this), "jsInterface");

And then the WebAppInterface:

public class WebAppInterface { ... }

Now, it just does not work. Has Cordova changed something recently? I seriously have no idea of what to do.

In both cases (previous version and new one), my main activity has this structure:

public class CordovaApp extends CordovaActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.init();
        loadUrl(Config.getStartUrl());
        ...
}
like image 570
josemmo Avatar asked May 01 '15 18:05

josemmo


2 Answers

After days looking for a solution, I finally get the app to work.

Cordova has changed the way to access Android webView. Developers using Cordova 5.0.0 and newer versions need to add this line to their main activity:

WebView wV = (WebView)appView.getEngine().getView();

And then, just call wV as usual. For example, to add a Javascript Interface:

wV.addJavascriptInterface(new WebAppInterface(this), "jsInterface");

I hope this answer will help other people who are confused about this new update.

like image 190
josemmo Avatar answered Oct 17 '22 03:10

josemmo


I was about to give up before i found your answer, which helped me on a related problem - thanks josemmo.

Maybe this will help others: After updating to Cordova 5 / Android 4 i couldn't get the shouldOverrideUrlLoading-Method of my WebViewClient to be triggered, because setting the WebViewClient on a newly created WebView

WebView webView = new WebView(this);
webView.setWebViewClient(new WebViewClient());

in the onCreate Method did nothing.

So the solution was to not create a new WebView, but to use the casted appView AND engine like so:

SystemWebViewEngine systemWebViewEngine = (SystemWebViewEngine) appView.getEngine();
WebViewClient myWebViewClient = new myWebViewClient(systemWebViewEngine);

WebView webView = (WebView) systemWebViewEngine.getView();
webView.setWebViewClient(myWebViewClient);

The custom WebViewClient class then needs a constructor:

public class myWebViewClient extends SystemWebViewClient {

    public myWebViewClient(SystemWebViewEngine systemWebViewEngine) {
        super(systemWebViewEngine);
    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        ...
    }
}

I kind of doubt that this is how it should be done, but at least its working.

like image 35
anga Avatar answered Oct 17 '22 04:10

anga