How to deal with cordova plugin when developing in browser?

て烟熏妆下的殇ゞ 提交于 2019-12-02 17:53:14

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/32191333/how-to-deal-with-cordova-plugin-when-developing-in-browser

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!