Search code examples
javaandroidcordovacordova-plugins

Cordova Plugin Expose JS Variable (Android) (CardFlight)


Is there a way to set a Global JS Variable from inside a cordova plugin?

My situation is this; I have a library that is initiated from an Anonymous class. Once initiated it has a function that can be called via a pointer.

The function has no return; and merely sets a variable;

        reader = new Reader(getApplicationContext(), new CardFlightDeviceHandler() {

                ...
                /* Response */
                @Override
                public void readerCardResponse(Card card) {
                    // TODO Auto-generated method stub

                    Toast.makeText(getApplicationContext(),
                            "Device swipe completed", Toast.LENGTH_SHORT)
                            .show();

                    mCard = card;

                    fillFieldsWithData(card);
                }
...

/* Call */
reader.beginSwipe();

(API Documentation) https://getcardflight.com/docs/api/android#initialization

(Class Initiatlization) https://github.com/CardFlight/android-demo/blob/master/android-demo/src/com/example/cardflight/MainActivity.java#L67

(Call) https://github.com/CardFlight/android-demo/blob/master/android-demo/src/com/example/cardflight/MainActivity.java#L164


Solution

  • Yes, this is possible.

    You can store a value via SharedPreferences and access this value in JS.

    You could use the NativeStorage plugin to retrieve a stored value.

    See this thread, here a JS value is stored via NativeStorage and accessed in Android. Your application should be the other way around. Store a value with SharedPreferences with the correct PREFS_NAME ("NativeStorage"). And get the value via NativeStorage.

    NativeStorage.getItem(<key>, function(value){}, function(error){});
    

    NativeStorage on NPM or Github.