Search code examples
javacordovaphonegap-pluginscordova-plugins

How can I return a string from a cordova custom plugin


While creating a custom plugin in cordova the return type of the execute methode is Boolean but for my application I want some String type to be returned that I can use in my javascript. But as the return type is Boolean, I am not able to do so.

Is there any way I can return some value from that execute method??


Solution

  • For Android and iOS, here's how you'd send a string from native back to the JS layer in your Cordova app:

    Android (Java)

    public class MyPlugin extends CordovaPlugin {
        public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
            String myString = "Some string";
            callbackContext.success(myString);
            return true;
        }
    }
    

    iOS (Objective-C)

    @implementation MyPlugin
    
    - (void) myAction:(CDVInvokedUrlCommand*)command {
        NSString* myString = @"Some string";
    
        CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:myString];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
    }
    

    Plugin bridge (Javascript)

    MyPlugin = {
        myAction: function(success, error){
            cordova.exec(success, error, "MyPlugin", "myAction", []);
        }
    }
    module.exports = MyPlugin;
    

    Your app (Javascript)

    function success(myString){
        alert(myString);
    }
    
    function error(error){
        alert(JSON.stringify(error));
    }
    
    MyPlugin.myAction(success, error);