Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / Apache

Using PhoneGap in Windows Store Applications

5.00/5 (2 votes)
14 Jan 2013CPOL7 min read 36.6K  
In this article you will learn about how to use PhoneGap with the new cutting edge Microsoft platform – Windows 8

Introduction

What is PhoneGap?

PhoneGap (previously called Apache Callback, now Apache Cordova) is an open-source mobile development framework produced by Nitobi, purchased by Adobe Systems. It enables developers to build applications for mobile devices using JavaScript, HTML5 and CSS3, instead of device specific languages such as C# or Objective-C. The resulting applications are hybrid, meaning that they are neither truly native (layout rendering is done via web views instead of the platform's native UI framework) nor purely web-based (because they are not just web apps, but are packaged as apps for distribution and have access to native device APIs).

Background

Windows 8 apps can be designed and coded using HTML, CSS and JavaScript just like PhoneGap apps can. And with very little effort you can use your skill and existing resources to have a modern looking Windows 8 app in no time.

PhoneGap and Windows 8 development are more similar than you realize

What you can take as an advantage when you create PhoneGap applications for Windows 8

  • Your skills, assets, and probably a lot of your existing pure HTML/CSS and JavaScript code will just work in a Windows 8 application.
  • You can update the look of your applications with very little effort by using the intrinsic styles for the basic HTML elements like <h1> and <button>, as well as the advanced Windows 8 controls like the app bar, date picker, flip view, and more.
  • Your code that interacts with the PhoneGap API (to handle things like file access, sensors and application lifecycle events) can be updated to use the WinJS library to accomplish the same things you were doing in PhoneGap.
  • Scenarios where you had to write PhoneGap plugins can be addressed by either finding the functionality in the expansive WinJS library, or by incorporating native code in a Windows 8 JavaScript app.

In this article we will talk about different ways to create Windows 8 Store applications with PhoneGap and will make a simple comparison between Windows 8 Applications with PhoneGap and those that use only WinJS

How to Create PhoneGap applications for Windows 8

There are three different ways to start with Windows 8 and PhoneGap

  • To create a new Windows 8 JavaScript project and add PhoneGap references manually
  • To start with PhoneGap startup project included in the distribution
  • To build a PhoneGap Windows 8 template and use it in Visual Studio 2012

Create a new Windows 8 JavaScript project and add PhoneGap references manually

What you need to start:

  • Windows 8
  • Visual Studio 2012 Professional or better, or Visual Studio 2012 Express for Windows 8

Create a PhoneGap Windows 8 Application

  • Download latest PhoneGap 2.x - http://phonegap.com/download or PhoneGap project from the Github : https://github.com/phonegap/phonegap/tree/master/lib/windows8
  • Create Blank JavaScript project.
  • Add “cordova-2.x.js” JavaScript file to your js folder. (Located in \lib\windows8)
  • Change default.html to index.html(optional).
    Microsoft continues to use default.html as the default page for use in websites, whereas most "open web" developers use index.html. (Plus it's likely that in the other platform variants of your project you are using index.html as the name of your default page.) To fix this, in Solution Explorer rename the default.html file to index.html. Then double-click the package.appxmanifest file and change the Start page value to index.html.
  • Add reference to cordova-2.x.js file from default.html/index.html page
  • Adding a ’deviceready’ handler... (optional)

You can read more details here.

You could start your Windows 8 PhoneGap application from JavaScript Windows Store Blank App template

Image 1

If you want to change default.html to index.html you need also change the name of the start page in the package.appxmanifest file.

Image 2

It is a good practice to add a ‘deviceready’ handler to be possible let your application to know when PhoGap libraries are fully loaded.

The Cordova deviceready event fires once Cordova has fully loaded. After the device has fired, you can safely make calls to Cordova function.

Image 3

Start with PhoneGap startup project included in the distribution

The official PhoneGap distribution and most of Apache Cordova source branches in the GtiHub have for each supported platform a template folder where is located a startup project. For some reasons most of distributions don’t include a ready for use Visual Studio project template but you could start your applications from a copy of this project.

Open the /lib/windows8/template folder from your distribution.

Image 4

Check the settings in your package.appxmanifest and you can continue with the development of applications with PhoneGap.

Image 5

Create a PhoneGap Windows 8 template

It is more convenient if you have Visual Studio project template for Windows Store PhoneGap applications. As it was mentioned before for each supported platform there is a template folder where is located a startup project, but for Windows 8 there is not a ready for use project template. You could create a Visual Studio 2012 project template from this startup project. For Windows 8 it is located in /lib/windows8/template folder from your distribution.

Most of Cordova implementations provide CordovaBuilder project that could generate a Visual Studio 2012 project templates. Unfortunately CordovaBuilder project for Windows 8 is not updated from several months. It works correct for some implementations like this https://github.com/01org/cordova-win8 but raise exceptions in the newest versions of PhoneGap because of project structure changes. More details how to build a Visual Studio Windows Store project template with CordovaBuilder you could find here. If you are using the latest version you need to update a CordovaBuilder.cs file.

Another approach is to create your template manually.

Custom project templates require the following items

  • A metadata (.vstemplate) file that Visual Studio uses to define how to display the project in the IDE and, if you have specified the appropriate properties, to customize how the project is created in the IDE.

  • A project file.

  • Code files such as Web forms, class files, and resource files.

In Cordova distribution you need add only a metadata file named MyTemplate.vstemplate and add a correct template settings.

A sample metadata (.vstemplate) file.

XML
 <VSTemplate Version="3.0.0" xmlns="http://schemas.microsoft.com/developer/vstemplate/2005" Type="Project">
  <TemplateData>
    <Name>Template-Cordova2</Name>
    <Description>&lt;No description available&gt;</Description>
    <ProjectType>JavaScript</ProjectType>
    <ProjectSubType>
    </ProjectSubType>
    <SortOrder>1000</SortOrder>
    <CreateNewFolder>true</CreateNewFolder>
    <DefaultName>Template-Cordova2</DefaultName>
    <ProvideDefaultName>true</ProvideDefaultName>
    <LocationField>Enabled</LocationField>
    <EnableLocationBrowseButton>true</EnableLocationBrowseButton>
    <Icon>__TemplateIcon.ico</Icon>
  </TemplateData>
  <TemplateContent>
    <Project TargetFileName="CordovaApp.jsproj" File="CordovaApp.jsproj" ReplaceParameters="true">
		<Folder Name="www" TargetFolderName="www">
		  <Folder Name="css" TargetFolderName="css">
			<ProjectItem ReplaceParameters="true" TargetFileName="index.css">index.css</ProjectItem>
		  </Folder>
		  <Folder Name="img" TargetFolderName="img">
			<ProjectItem ReplaceParameters="false" 
			  TargetFileName="logo.png">logo.png</ProjectItem>
			<ProjectItem ReplaceParameters="false" 
			  TargetFileName="smalllogo.png">smalllogo.png</ProjectItem>
			<ProjectItem ReplaceParameters="false" 
			  TargetFileName="splashscreen.png">splashscreen.png</ProjectItem>
			<ProjectItem ReplaceParameters="false" 
			  TargetFileName="storelogo.png">storelogo.png</ProjectItem>
		  </Folder>
		  <Folder Name="js" TargetFolderName="js">			
			<ProjectItem ReplaceParameters="true" TargetFileName="index.js">index.js</ProjectItem>
		  </Folder>
		  <ProjectItem ReplaceParameters="true" TargetFileName="cordova-2.3.0.js">cordova-2.3.0.js</ProjectItem>
		  <ProjectItem ReplaceParameters="true" TargetFileName="index.html">index.html</ProjectItem>
		</Folder >
      <ProjectItem ReplaceParameters="false" TargetFileName="package.appxmanifest">package.appxmanifest</ProjectItem>
      <ProjectItem ReplaceParameters="false" TargetFileName="CordovaApp_TemporaryKey.pfx">CordovaApp_TemporaryKey.pfx</ProjectItem>
    </Project>
  </TemplateContent>
</VSTemplate>

More details about Visual Studio project templates you could find here.

When you are ready just zip the all content of your /lib/windows8/template folder .

Copy your zip file in your \My Documents\Visual Studio 2012\Templates\ProjectTemplates\Language\ folder. In this case language is JavaScript.

Then open a new instance of Visual Studio 2012 and select File->New->Project you will see your project template.

Image 6

When you select Template-Cordova2 item from the list you will have a Windows 8 with PhoneGap startup project.

Image 7

Image 8

PhoneGap vs WinJS

The main difference between PhoneGap and WinJS is in the API. When you need to access some device resources you need to use different APIs . For example for geolocation in Cordova you need to use navigator.geolocation.getCurrentPosition(…) function. In WinJS library you need to create an instance of Geolocator:

var geolocator = 
Windows.Devices.Geolocation.Geolocator();
and then to call geolocator.getGeopositionAsync().

A showLocation function using PhoneGap

JavaScript
function showLocation() {
	navigator.geolocation.getCurrentPosition(function (location) {
		$("#locationResult").innerHTML = "Latitude: <strong>" + 
		  location.coords.latitude + "</strong><br/>Longitude: <strong>" + 
		  location.coords.longitude + "</strong>";
	}, function (err) {
		$("#locationResult").textContent = "Error getting location";
	}, { timeout: 30000, enableHighAccuracy: true });
}

The same showLocation function using WinJS

JavaScript
function showLocation() {
	var geolocator = Windows.Devices.Geolocation.Geolocator();
	geolocator.desiredAccuracy = Windows.Devices.Geolocation.PositionAccuracy.high;
	geolocator.getGeopositionAsync().then(getCurPosHandler, errHandler);
}

Windows Store JavaScript Applications with PhoneGap

index.html code

HTML
 <!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>PhoneGap Demo App</title>
   

    <!-- WinJS references -->
    <link href="http://www.codeproject.com/Microsoft.WinJS.1.0/css/ui-dark.css" rel="stylesheet" />
    <script src="http://www.codeproject.com/Microsoft.WinJS.1.0/js/base.js"></script>
    <script src="http://www.codeproject.com/Microsoft.WinJS.1.0/js/ui.js"></script>

     <!-- Cordova -->
    <script src="http://www.codeproject.com/js/cordova-2.2.0.js"></script>

    <!-- PhoneGapDemoApp references -->
    <link href="http://www.codeproject.com/css/default.css" rel="stylesheet" />
    <script src="http://www.codeproject.com/js/default.js"></script>
</head>
<body>     
    <p>Content goes here</p>
    <h1>PhoneGap for Windows 8 - Demo</h1>
     <script type="text/javascript">

         console.log("Subscribing top  deviceready event...");
         document.addEventListener("deviceready", function () {

             navigator.notification.alert("This device is ready!");

         });

    </script>    
    <p>
        <strong>Location</strong>
        <button id="btnGeoLocation">Get Current Location</button><br />        
    </p>
    <div id="locationResult">

default.js code

JavaScript
// For an introduction to the Blank template, see the following documentation:
// http://go.microsoft.com/fwlink/?LinkId=232509
(function () {
    "use strict";

    WinJS.Binding.optimizeBindingReferences = true;

    var app = WinJS.Application;
    var activation = Windows.ApplicationModel.Activation;


    function $(element) {
        return document.querySelector(element);
    }

    function showLocation() {
        navigator.geolocation.getCurrentPosition(function (location) {
            $("#locationResult").innerHTML = "Latitude: <strong>" + 
              location.coords.latitude + "</strong><br/>Longitude: <strong>" + 
              location.coords.longitude + "</strong>";
        }, function (err) {
            $("#locationResult").textContent = "Error getting location";
        }, { timeout: 30000, enableHighAccuracy: true });
    }

    app.onactivated = function (args) {
        if (args.detail.kind === activation.ActivationKind.launch) {
            if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
                // TODO: This application has been newly launched. Initialize
                // your application here.
                $("#btnGeoLocation").addEventListener("click", showLocation, false);
            } else {
                // TODO: This application has been reactivated from suspension.
                // Restore application state here.
            }
            args.setPromise(WinJS.UI.processAll());

           
        }
    };

    app.oncheckpoint = function (args) {
        // TODO: This application is about to be suspended. Save any state
        // that needs to persist across suspensions here. You might use the
        // WinJS.Application.sessionState object, which is automatically
        // saved and restored across suspension. If you need to complete an
        // asynchronous operation before your application is suspended, call
        // args.setPromise().
    };

    app.start();
})();
  • Create a Windows Store PhoneGap application

You need to turn on Location capabilities

Image 9

Geolocation application screen.

Image 10

Windows Store JavaScript Geolocation Application with WinJS

Here is the code of the default.html file.

HTML
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>WinJS Demo App</title>

    <!-- WinJS references -->
    <link href="http://www.codeproject.com/Microsoft.WinJS.1.0/css/ui-dark.css" rel="stylesheet" />
    <script src="http://www.codeproject.com/Microsoft.WinJS.1.0/js/base.js"></script>
    <script src="http://www.codeproject.com/Microsoft.WinJS.1.0/js/ui.js"></script>

    <!-- WinJSDemoApp references -->
    <link href="http://www.codeproject.com/css/default.css" rel="stylesheet" />
    <script src="http://www.codeproject.com/js/default.js"></script>
</head>
<body>
    <p>Content goes here</p>
    <h1>WinJS for Windows 8 - Demo</h1>

        <p>
        <strong>Location</strong>
        <button id="btnGeoLocation">Get Current Location</button><br />
        

    </p>
    <div id="locationResult"></div>
</body>
</html>

Source code of the default.js file is shown below.

JavaScript
// For an introduction to the Blank template, see the following documentation:
// http://go.microsoft.com/fwlink/?LinkId=232509
(function () {
    "use strict";

    WinJS.Binding.optimizeBindingReferences = true;

    var app = WinJS.Application;
    var activation = Windows.ApplicationModel.Activation;

    function showLocation() {
        var geolocator = Windows.Devices.Geolocation.Geolocator();
        geolocator.desiredAccuracy = Windows.Devices.Geolocation.PositionAccuracy.high;
        geolocator.getGeopositionAsync().then(getCurPosHandler, errHandler);


    }

    function getCurPosHandler(pos) {
        document.getElementById('locationResult').innerHTML = "Latitude: <strong>" + 
          pos.coordinate.latitude + "</strong><br/>Longitude: <strong>" + 
          pos.coordinate.longitude + "</strong>";
    }


    function errHandler(e) {
        document.getElementById('locationResult').innerHTML = e.message;
    }


    app.onactivated = function (args) {
        if (args.detail.kind === activation.ActivationKind.launch) {
            if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
                // TODO: This application has been newly launched. Initialize
                // your application here.
                document.getElementById('btnGeoLocation').addEventListener("click", showLocation, false);
            } else {
                // TODO: This application has been reactivated from suspension.
                // Restore application state here.
            }
            args.setPromise(WinJS.UI.processAll());
        }
    };

    app.oncheckpoint = function (args) {
        // TODO: This application is about to be suspended. Save any state
        // that needs to persist across suspensions here. You might use the
        // WinJS.Application.sessionState object, which is automatically
        // saved and restored across suspension. If you need to complete an
        // asynchronous operation before your application is suspended, call
        // args.setPromise().
    };

    app.start();
})();

Conclusions

It is a pretty easy to create Windows 8 applications with PhoneGap. Many people will ask - why PhoneGap after we are able to create Windows Store WinJS applications. The advantage of using PhoneGap e when you want an application to be compiled for different platforms (Windows 8 and various mobile platforms) without changes in your HTML and JavaScript code. If you need to create an application only for Windows Store with JavaScript the native choice will be to use WinJS except the case when you already have experience with PhoneGap for some of the mobile platforms. In all cases PhoneGap support for Windows 8 provides additional opportunities to create portable applications with JavaScript code. All WEB developers who know PhoneGap can easily to create Windows Store applications without additional effort.

Source code of the Windows 8 PhoneGap geolocation application is available here.

Windows 8 sample application - geolocation with WinJS is available here.

You could download Visual Studio 2012 Windows Store PhoneGap template from this link.

As always, you can follow me on Twitter @mihailmateev and stay in touch on Facebook, Google+ and LinkedIn!

History

The new version of Apache Cordova 2.3.0, released on 7th of January 2013. You are welcome to go download and get started with the direct link to the RTM or r via the tags page atgithub.com/phonegap/phonegap/tags .


License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)