Search code examples
javascriptcordovacordova-plugins

How to deal with cordova plugin when developing in browser?


I'm developing an application Ionic, Angular and Cordova and I'm looking for the best way to call Cordova plugins in Javascript while developing in the browser. What is the best practice? And how can I make it DRY?

Let's say I'm using the Cordova globalization plugin. In order to prevent any errors when testing inside a browser, I would have to wrap the code inside a try and catch like this:

try {
   navigator.globalization.getPreferredLanguage(onSuccess, onError);
}
catch (e) {
   console.log(e);
}

Or I would test if navigator.globalization is defined like this:

 if(navigator.globalization) {
     navigator.globalization.getPreferredLanguage(onSuccess, onError);
 }

But is there any way I can avoid doing that every time I need to call a Cordova plugin?

Thanks for your help.


Solution

  • As cordova.js is only available when you are running application in device or emulator. So there is no way that you can use cordova plugins in browsers.As you need to put a check if(navigator.globalization) on every plugin call for testing on browsers, so i will suggest you to make your own wrapper or functions above these calls, some sort of global function which will call these plugins functions. Here is a sample with plain javascript.

    function MyGlobalizationService(){
    };
    
    MyGlobalizationService.prototype.getPreferredLanguage = function(onSuccess, onError){
     if(navigator.globalization) {
         navigator.globalization.getPreferredLanguage(onSuccess, onError);
     }
    }
    
    window.myGlobalizationService = new MyGlobalizationService();
    

    And then use window.myGlobalizationService functions anywhere in your application.