Saturday, 29 December 2012

Hello World Application on OS X in HTML & JavaScript with node-webkit

JavaScript is the current programming hot potato, it's already possible to build Windows 8 applications in HTML & JavaScript with the excellent tools and training that Microsoft provide but what about OS X & Linux?

Another interesting way of writing HTML & JavaScript applications for OS X (and indeed Windows & Linux) is by using node-webkit.

This tutorial steps through creating a simple hello world style application and then using node-webkit to package and run it on OS X.

Full source code can be downloaded from here.

Prerequisites

Download node-webkit from here: https://github.com/rogerwang/node-webkit

Download the latest version of jQuery from here: http://jquery.com/

Step 1- Create our Hello World web application

What we want is quite simple, a button that has a click event that updates a label.

Let's get started with some HTML, create a file called index.html and populate it with this html:


<!DOCTYPE html>
<html>
<head>
<title>Hello World</title>
<script type="text/javascript" src="jquery-1.8.3.min.js"></script>
<script type="text/javascript" src="index.events.js"></script>
</head>
<body>
<button id="mybutton">Press Me!</button>
<label id="mylabel"></label>
</body>
</html>
view raw index.html hosted with ❤ by GitHub



We also need to create the JavaScript that deals with the button click event.

Create another new file and save it as index.events.js and populate it with this JavaScript:

$(document).ready(function(){
$('#mybutton').click( function() {
$('#mylabel').text('Hello World');
});
});
view raw index.events.js hosted with ❤ by GitHub



Now open index.html and press the button:

Not very exciting, but it can be seen here that it's working and running in Safari. 

Step 2 - Bundle our web application as a node-webkit application

To create a node-webkit application we need to create one further file called package.json:

{
"name": "Hello World",
"description": "Hello World Demo",
"version": "1",
"main": "index.html",
"window": {
"toolbar": false,
"width": 500,
"height": 200
}
}
view raw package.json hosted with ❤ by GitHub
Now we have four files in our directory:

    index.html
    index.events.js
    jquery-1.8.3.min.js
    package.json

Create a ZIP file with the above four files and call it HelloWorld.nw.

Copy the node-webkit application into the above project directory and run it:



And there we go - our Hello World application running on OS X - source code for this demo here.



For more information on running and packaging the application see these links:

https://github.com/rogerwang/node-webkit/wiki/How-to-run-apps

https://github.com/rogerwang/node-webkit/wiki/How-to-package-and-distribute-your-apps



No comments:

Post a Comment