Cordova – Whitelist

Cordova – Whitelist ”; Previous Next This plugin allows us to implement whitelist policy for app”s navigation. When we create a new Cordova project, the whitelist plugin is installed and implemented by default. You can open the config.xml file to see allow-intent default settings provided by Cordova. Navigation Whitelist In the simple example below we are allowing links to some external URL. This code is placed in config.xml. Navigation to file:// URLs is allowed by default. <allow-navigation href = “http://example.com/*” /> The asterix sign, *, is used to allow navigation to multiple values. In the above example, we are allowing navigation to all sub-domains of the example.com. The same can be applied to protocol or prefix to the host. <allow-navigation href = “*://*.example.com/*” /> Intent Whitelist There is also the allow-intent element which is used to specify which URLs are allowed to open the system. You can see in the config.xml that Cordova already allowed most of the needed links for us. Network Request Whitelist When you look inside config.xml file, there is <access origin=”*” /> element. This element allows all network requests to our app via Cordova hooks. If you want to allow only specific requests, you can delete it from the config.xml and set it yourself. The same principle is used as in previous examples. <access origin = “http://example.com” /> This will allow all network requests from http://example.com. Content Security Policy You can see the current security policy for your app inside the head element in index.html. <meta http-equiv = “Content-Security-Policy” content = “default-src ”self” data: gap: https://ssl.gstatic.com ”unsafe-eval”; style-src ”self” ”unsafe-inline”; media-src *”> This is default configuration. If you want to allow everything from the same origin and example.com, then you can use − <meta http-equiv = “Content-Security-Policy” content = “default-src ”self” foo.com”> You can also allow everything, but restrict CSS and JavaScript to the same origin. <meta http-equiv = “Content-Security-Policy” content = “default-src *; style-src ”self” ”unsafe-inline”; script-src ”self” ”unsafe-inline” ”unsafe-eval””> Since this is a beginners’ tutorial, we are recommending the default Cordova options. Once you get familiar with Cordova, you can try some different values. Print Page Previous Next Advertisements ”;

Cordova – Discussion

Discuss Cordova ”; Previous Next Cordova is a platform that is used for building mobile apps using HTML, CSS and JS. We can think of Cordova as a container for connecting our web app with native mobile functionalities. Web applications cannot use native mobile functionalities by default. This is where Cordova comes into picture. It offers a bridge for connection between web app and mobile device. By using Cordova, we can make hybrid mobile apps that can use camera, geolocation, file system and other native mobile functions. Print Page Previous Next Advertisements ”;

Cordova – Useful Resources

Cordova – Useful Resources ”; Previous Next The following resources contain additional information on Cordova. Please use them to get more in-depth knowledge on this topic. Learn Cordova From Scratch – Visual Studio and Mac 46 Lectures 2 hours Skillbakery More Detail Learn Apache Cordova using Visual Studio 2015 & Command line 17 Lectures 1 hours Nilay Mehta More Detail Ionic 5+ from Beginner to Advanced – Build Food Delivery App Featured 185 Lectures 46.5 hours Nikhil Agarwal More Detail Print Page Previous Next Advertisements ”;

Cordova – Environment Setup

Cordova – Environment Setup ”; Previous Next In this chapter, we will understand the Environment Setup of Cordova. To begin with the setup, we need to first install a few components. The components are listed in the following table. S.No Software & Description 1 NodeJS and NPM NodeJS is the platform needed for Cordova development. Check out our NodeJS Environment Setup for more details. 2 Android SDK For Android platform, you need to have Android SDK installed on your machine. Check out Android Environment Setup for more details. 3 XCode For iOS platform, you need to have xCode installed on your machine. Check out iOS Environment Setup for more details Installing Cordova Before we start, you need to know that we will use Windows command prompt in our tutorial. Step 1 – Installing git Even if you don”t use git, it should be installed since Cordova is using it for some background processes. You can download git here. After you install git, open your environment variable. Right-Click on Computer Properties Advanced System settings Environment Variables System Variables Edit Copy the following at the end of the variable value field. This is default path of the git installation. If you installed it on a different path you should use that instead of our example code below. ;C:Program Files (x86)Gitbin;C:Program Files (x86)Gitcmd Now you can type git in your command prompt to test if the installation is successful. Step 2 – Installing Cordova This step will download and install Cordova module globally. Open the command prompt and run the following − C:Usersusername>npm install -g cordova You can check the installed version by running − C:Usersusername>cordova -v This is everything you need to start developing the Cordova apps on Windows operating system. In our next tutorial, we will show you how to create first application. Print Page Previous Next Advertisements ”;

Cordova – Battery Status

Cordova – Battery Status ”; Previous Next This Cordova plugin is used for monitoring device”s battery status. The plugin will monitor every change that happens to device”s battery. Step 1 – Installing Battery Plugin To install this plugin, we need to open the command prompt window and run the following code. C:UsersusernameDesktopCordovaProject>cordova plugin add cordova-pluginbattery-status Step 2 – Add Event Listener When you open the index.js file, you will find the onDeviceReady function. This is where the event listener should be added. window.addEventListener(“batterystatus”, onBatteryStatus, false); Step 3 – Create Callback Function We will create the onBatteryStatus callback function at the bottom of the index.js file. function onBatteryStatus(info) { alert(“BATTERY STATUS: Level: ” + info.level + ” isPlugged: ” + info.isPlugged); } When we run the app, an alert will be triggered. At the moment, the battery is 100% charged. When the status is changed, a new alert will be displayed. The battery status shows that the battery is now charged 99%. If we plug in the device to the charger, the new alert will show that the isPlugged value is changed to true. Additional Events This plugin offers two additional events besides the batterystatus event. These events can be used in the same way as the batterystatus event. S.No Event & Details 1 batterylow The event is triggered when the battery charge percentage reaches low value. This value varies with different devices. 2 batterycritical The event is triggered when the battery charge percentage reaches critical value. This value varies with different devices. Print Page Previous Next Advertisements ”;

Cordova – Device Orientation

Cordova – Device Orientation ”; Previous Next Compass is used to show direction relative to geographic north cardinal point. Step 1 – Install Device Orientation plugin Open the command prompt window and run the following. C:UsersusernameDesktopCordovaProject>cordova plugin add cordova-plugindevice-orientation Step 2 – Add Buttons This plugin is similar to the acceleration plugin. Let us now create two buttons in index.html. <button id = “getOrientation”>GET ORIENTATION</button> <button id = “watchOrientation”>WATCH ORIENTATION</button> Step 3 – Add Event Listeners Now, we will add event listeners inside the onDeviceReady function in index.js. document.getElementById(“getOrientation”).addEventListener(“click”, getOrientation); document.getElementById(“watchOrientation”).addEventListener(“click”, watchOrientation); Step 4 – Creating Functions We will create two functions; the first function will generate the current acceleration and the other will check on the orientation changes. You can see that we are using the frequency option again to keep a watch on changes that occur every three seconds. function getOrientation() { navigator.compass.getCurrentHeading(compassSuccess, compassError); function compassSuccess(heading) { alert(”Heading: ” + heading.magneticHeading); }; function compassError(error) { alert(”CompassError: ” + error.code); }; } function watchOrientation(){ var compassOptions = { frequency: 3000 } var watchID = navigator.compass.watchHeading(compassSuccess, compassError, compassOptions); function compassSuccess(heading) { alert(”Heading: ” + heading.magneticHeading); setTimeout(function() { navigator.compass.clearWatch(watchID); }, 10000); }; function compassError(error) { alert(”CompassError: ” + error.code); }; } Since the compass plugin is almost the same as the acceleration plugin, we will show you an error code this time. Some devices do not have the magnetic sensor that is needed for the compass to work. If your device doesn”t have it, the following error will be displayed. Print Page Previous Next Advertisements ”;

Cordova – Events

Cordova – Events ”; Previous Next There are various events that can be used in Cordova projects. The following table shows the available events. S.No Events & Details 1 deviceReady This event is triggered once Cordova is fully loaded. This helps to ensure that no Cordova functions are called before everything is loaded. 2 pause This event is triggered when the app is put into background. 3 resume This event is triggered when the app is returned from background. 4 backbutton This event is triggered when the back button is pressed. 5 menubutton This event is triggered when the menu button is pressed. 6 searchbutton This event is triggered when the Android search button is pressed. 7 startcallbutton This event is triggered when the start call button is pressed. 8 endcallbutton This event is triggered when the end call button is pressed. 9 volumedownbutton This event is triggered when the volume down button is pressed. 10 volumeupbutton This event is triggered when the volume up button is pressed. Using Events All of the events are used almost the same way. We should always add event listeners in our js instead of the inline event calling since the Cordova Content Security Policy doesn”t allow inline Javascript. If we try to call event inline, the following error will be displayed. The right way of working with events is by using addEventListener. We will understand how to use the volumeupbutton event through an example. document.addEventListener(“volumeupbutton”, callbackFunction, false); function callbackFunction() { alert(”Volume Up Button is pressed!”); } Once we press the volume up button, the screen will display the following alert. Handling Back Button We should use the Android back button for app functionalities like returning to the previous screen. To implement your own functionality, we should first disable the back button that is used to exit the App. document.addEventListener(“backbutton”, onBackKeyDown, false); function onBackKeyDown(e) { e.preventDefault(); alert(”Back Button is Pressed!”); } Now when we press the native Android back button, the alert will appear on the screen instead of exiting the app. This is done by using the e.preventDefault() command. Print Page Previous Next Advertisements ”;

Cordova – Config.xml File

Cordova – config.xml File ”; Previous Next The config.xml file is the place where we can change the configuration of the app. When we created our app in the last tutorial, we set reverse domain and name. The values can be changed in the config.xml file. When we create the app, the default config file will also be created. The following table explains configuration elements in config.xml. config.xml Configuration Table S.No Element & Details 1 widget The app reverse domain value that we specified when creating the app. 2 name The name of the app that we specified when creating the app. 3 description Description for the app. 4 author Author of the app. 5 content The app”s starting page. It is placed inside the www directory. 6 plugin The plugins that are currently installed. 7 access Used to control access to external domains. The default origin value is set to &ast; which means that access is allowed to any domain. This value will not allow some specific URLs to be opened to protect information. 8 allow-intent Allows specific URLs to ask the app to open. For example, <allow-intent href = “tel:*” /> will allow tel: links to open the dialer. 9 platform The platforms for building the app. Print Page Previous Next Advertisements ”;

Cordova – Media

Cordova – Media ”; Previous Next Cordova media plugin is used for recording and playing audio sounds in Cordova apps. Step 1 – Installing Media Plugin Media plugin can be installed by running the following code in command prompt window. C:UsersusernameDesktopCordovaProject>cordova plugin add cordova-plugin-media Step 2 – Add Buttons In this tutorial, we will create simple audio player. Let”s create buttons that we need in index.html. <button id = “playAudio”>PLAY</button> <button id = “pauseAudio”>PAUSE</button> <button id = “stopAudio”>STOP</button> <button id = “volumeUp”>VOLUME UP</button> <button id = “volumeDown”>VOLUME DOWN</button> Step 3 – Add Event Listeners Now we need to add event listeners for our buttons inside onDeviceReady function inside index.js. document.getElementById(“playAudio”).addEventListener(“click”, playAudio); document.getElementById(“pauseAudio”).addEventListener(“click”, pauseAudio); document.getElementById(“stopAudio”).addEventListener(“click”, stopAudio); document.getElementById(“volumeUp”).addEventListener(“click”, volumeUp); document.getElementById(“volumeDown”).addEventListener(“click”, volumeDown); Step 4A – Play Function The first function that we are going to add is playAudio. We are defining myMedia outside of the function because we want to use it in functions that are going to be added later (pause, stop, volumeUp and volumeDown). This code is placed in index.js file. var myMedia = null; function playAudio() { var src = “/android_asset/www/audio/piano.mp3”; if(myMedia === null) { myMedia = new Media(src, onSuccess, onError); function onSuccess() { console.log(“playAudio Success”); } function onError(error) { console.log(“playAudio Error: ” + error.code); } } myMedia.play(); } We can click PLAY button to start the piano music from the src path. Step 4B – Pause and Stop Functions The next functions that we need is pauseAudio and stopAudio. function pauseAudio() { if(myMedia) { myMedia.pause(); } } function stopAudio() { if(myMedia) { myMedia.stop(); } myMedia = null; } Now we can pause or stop the piano sound by clicking PAUSE or STOP buttons. Step 4C – Volume Functions To set the volume, we can use setVolume method. This method takes parameter with values from 0 to 1. We will set starting value to 0.5. var volumeValue = 0.5; function volumeUp() { if(myMedia && volumeValue < 1) { myMedia.setVolume(volumeValue += 0.1); } } function volumeDown() { if(myMedia && volumeValue > 0) { myMedia.setVolume(volumeValue -= 0.1); } } Once we press VOLUME UP or VOLUME DOWN we can change the volume value by 0.1. The following table shows other methods that this plugin provides. S.No Method & Details 1 getCurrentPosition Returns current position of an audio. 2 getDuration Returns duration of an audio. 3 play Used for starting or resuming audio. 4 pause Used for pausing audio. 5 release Releases the underlying operating system”s audio resources. 6 seekTo Used for changing position of an audio. 7 setVolume Used for setting volume for audio. 8 startRecord Start recording an audio file. 9 stopRecord Stop recording an audio file. 10 stop Stop playing an audio file. Print Page Previous Next Advertisements ”;

Cordova – Storage

Cordova – Storage ”; Previous Next We can use storage API available for storing data on the client apps. This will help the usage of the app when the user is offline and it can also improve performance. Since this tutorial is for beginners, we will show you how to use local storage. In one of our later tutorials, we will show you the other plugins that can be used. Step 1 – Adding Buttons We will create four buttons in the index.html file. The buttons will be located inside the div class = “app” element. <button id = “setLocalStorage”>SET LOCAL STORAGE</button> <button id = “showLocalStorage”>SHOW LOCAL STORAGE</button> <button id = “removeProjectFromLocalStorage”>REMOVE PROJECT</button> <button id = “getLocalStorageByKey”>GET BY KEY</button> It will produce the following screen − Step 2 – Adding Event Listeners Cordova security policy doesn”t allow inline events so we will add event listeners inside index.js files. We will also assign window.localStorage to a localStorage variable that we will use later. document.getElementById(“setLocalStorage”).addEventListener(“click”, setLocalStorage); document.getElementById(“showLocalStorage”).addEventListener(“click”, showLocalStorage); document.getElementById(“removeProjectFromLocalStorage”).addEventListener (“click”, removeProjectFromLocalStorage); document.getElementById(“getLocalStorageByKey”).addEventListener (“click”, getLocalStorageByKey); var localStorage = window.localStorage; Step 3 – Creating Functions Now we need to create functions that will be called when the buttons are tapped. First function is used for adding data to local storage. function setLocalStorage() { localStorage.setItem(“Name”, “John”); localStorage.setItem(“Job”, “Developer”); localStorage.setItem(“Project”, “Cordova Project”); } The next one will log the data we added to console. function showLocalStorage() { console.log(localStorage.getItem(“Name”)); console.log(localStorage.getItem(“Job”)); console.log(localStorage.getItem(“Project”)); } If we tap SET LOCAL STORAGE button, we will set three items to local storage. If we tap SHOW LOCAL STORAGE afterwards, the console will log items that we want. Let us now create function that will delete the project from local storage. function removeProjectFromLocalStorage() { localStorage.removeItem(“Project”); } If we click the SHOW LOCAL STORAGE button after we deleted the project, the output will show null value for the project field. We can also get the local storage elements by using the key() method which will take the index as an argument and return the element with corresponding index value. function getLocalStorageByKey() { console.log(localStorage.key(0)); } Now when we tap the GET BY KEY button, the following output will be displayed. NOTE When we use the key() method, the console will log the job instead of the name even though we passed argument 0 to retrieve the first object. This is because the local storage is storing data in alphabetical order. The following table shows all the available local storage methods. S.No Methods & Details 1 setItem(key, value) Used for setting the item to local storage. 2 getItem(key) Used for getting the item from local storage. 3 removeItem(key) Used for removing the item from local storage. 4 key(index) Used for getting the item by using the index of the item in local storage. This helps sort the items alphabetically. 5 length() Used for retrieving the number of items that exists in local storage. 6 clear() Used for removing all the key/value pairs from local storage. Print Page Previous Next Advertisements ”;