Mark
Mark

Reputation: 5088

Making the calls directly from java to javascript with Phonegap

I'm writing a native plugin to raise an event in JavaScript when the keyboard is showing. I do this:

appView.sendJavascript("cordova.fireWindowEvent('show_keyboard')")

In my JavaScript I then do something like:

window.addEventListener('show_keyboard', handler);

However, this has been flagged as a big no no in PhoneGap by a PhoneGap expert on the team. What is wrong with this approach?

Upvotes: 6

Views: 1538

Answers (2)

Whymarrh
Whymarrh

Reputation: 13565

Looking for an answer drawing from credible and/or official sources.

Well I too am no PhoneGap expert, but Apache Cordova, the engine that powers PhoneGap has its source on GitHub.

What does the source say?

Well, as an example, let's look at how Cordova sends its volumedownbutton event. I present lines 613–621 of CordovaWebView.java:

if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
    this.loadUrl("javascript:cordova.fireDocumentEvent('volumedownbutton');");
    return true;
}
// If volumeup key
else if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
    this.loadUrl("javascript:cordova.fireDocumentEvent('volumeupbutton');");
    return true;
}

It would seem that Cordova employs a similar approach to sending events to JavaScript.

What's wrong with what you have?

I am not sure what the exact issue was that your coworker raised, but it does seem that sendJavascript is deprecated. So, there's that. But if your appView is a CordovaWebView, the you can just call loadUrl in the same way the that Cordova itself does it (as shown above).

Upvotes: 3

Manuel Allenspach
Manuel Allenspach

Reputation: 12735

I am no phonegap expert, but why don't you just call the method directly instead of using listeners?

for example

function keyboardShown() {
    alert("test"); //or other code
}

and

appView.sendJavascript("keyboardShown();")

This way you remove the overhead which you have through the listener.

If this still doesn't satisfy your phonegap expert, ask him what he would do to improve this code.

Upvotes: 0

Related Questions