Accessing Cordova Config Info From JavaScript Without Plugins

I wanted to access the current build number for analytics, but there seemed to be no easy way to get at the info that Cordova puts into the plist file (Xcode) and AndroidManifest.xml (Android Studio).

My solution is to copy those to files into the www folder at build time and then load them with AJAX. It means adding the following line in the iOS project in ios/cordova/lib/copy-www-build-step.js, somewhere near the end:

shell.cp('-f', path.join(path.dirname(PROJECT_FILE_PATH), path.basename(PROJECT_FILE_PATH, '.xcodeproj'), '*.plist'), dstWwwDir);

As part of the build process, this copies the plist file into the root web directory as it’s deployed onto the device (meaning there are no changes to the source filesystem). So if it doesn’t seem to work, write some kind of check to see if the file actually gets copied.

Then in Android Studio, inside build.gradle for the app module, right before the line that starts android {:

task copyFiles(type: Copy) {
description = 'copying some file(s)....'
from "../app/AndroidManifest.xml"
into '../app/src/main/assets/www/'
preBuild.dependsOn copyFiles

Unlike the Xcode version, this copies AndroidManifest.xml into the www root directory before it’s deployed to the device, so the file will appear inside the www directory. It’s overwritten each time in case there are any changes.

Then inside JavaScript, to access data within those files I used jQuery to parse AndroidManifest.xml and a library called Plist Parser to make iOS just as easy. Plist Parser turns the annoyingly structured file into a JSON object that’s trivial to navigate through.

The JavaScript code, assuming there’s a check for platform somewhere else, is below. I mainly wanted CFBundleVersion (iOS) and android:versionCode (Android), but you can access anything else in the file too:

if (platform == 'android') {
url: 'AndroidManifest.xml',
dataType: 'text',
success: function (response) {
var xml = $(jQuery.parseXML(response));
var root = xml.find('manifest');
if (root) {
if (root.attr('android:versionCode')) {
var app_version = root.attr('android:versionCode');
if (root.attr('package')) {
var app_id = root.attr('package');
error: function (response) {
//Will have to do without data from plist file
} else if (platform == 'ios') {
url: '[your plist filename]',
dataType: 'text',
success: function (xmlString) {
var plist = PlistParser.parse(xmlString);
if (plist) {
if (plist['CFBundleVersion']) {
var app_version = plist['CFBundleVersion'];
if (plist['CFBundleVersion']) {
var app_id = plist['CFBundleIdentifier'];
error: function (response) {
//Will have to do without data from plist file

I’ve yet to see whether running cordova build ios or cordova build android overwrites the build process changes or not.

Build an HTML5 Game: Some Reviews

Build an HTML5 Game CoverI’ve found three decent reviews for my book “Build an HTML5 Game“, and especially pleasing is the fact that two of them seem to be from exactly the target audience i.e. developers with existing web skills who didn’t realise how easy it would be to use those skills to build a game.

First up, there’s Matthew Helmke’s review which you can read on his site:

I really enjoyed reading Build an HTML5 Game. The writing is clear and easy to follow, the examples are good, and the concepts provide a solid foundation on which you can build. This is not a comprehensive “everything you will ever need or want to know about game programming” sort of book, but rather a clean and enjoyable entry that helps you over the first hurdle of writing that first game. It then gives you ideas and tips to help you know what else is out there so you have a bit of a roadmap to continue learning as you figure out what sorts of games you want to create.

And then there’s a review on I Programmer:

The descriptions of all of the ideas are clear and easy to follow but only if you already know something about the technologies being used. This is not a book for trying to learn JavaScript or even HTML/CSS. It would make a good second level course on the techologies, but only if you were interested in building a game.

And finally this review by Sandra Henry-Stocker on IT World:

The starting point of Build an HTML5 Game: A Developer’s Guide with CSS and JavaScript is something that completely snuck up on me. In my time as a volunteer webmaster, I’d never considered taking my web skills much further than a church web site with just a tad of moving text and a slide show “walk” along the nature trail. The features of HTML5 that have made it a contender for game development were simply lost on me. With this book, the proverbial lights came on. And while I haven’t yet jumped in and tried to build my own game, I now understand what is required and might just give it a shot.

Fingers crossed that this helps the book sell, of course, but they’re great to see in their own right.

Build An HTML5 Game – Answers To Exercises

My Build An HTML5 Game book is finally on the way, and the website to go with it is live too.

As well as info about the book it serves three main purposes:

  1. A place to see and play the Bubble Shooter game developed in the book
  2. Assets such as images and sounds to make the game
  3. Solutions to the exercises at the end of each chapter in the book

The last are only suggested solutions and there’s a comment form below and I’m hoping others will be able to improve on my coding here.

Build an HTML5 Game – 40% Early Access Discount

Build an HTML5 GameMy book Build an HTML5 Game in going to be out in a couple of months, and until around 4pm on January 31st 2015 you can get 40% off with the discount code BRIGHTANDEARLY if you buy it here:

The discount applies to ebooks or the physical copy too, although it’s only if you’re in the United States that I guess the physical version makes sense, until it’s more widely distributed sometime in March.

Build an HTML5 Game

Make your own game without learning any new languages! With just HTML, CSS, and JavaScript in your toolbox, you can create a truly cross-platform game, playable on both desktop and mobile browsers.

In Build an HTML5 Game, author Karl Bunyan shows you how to create browser-based games by walking you through an in-depth tutorial on building a classic favorite, the bubble shooter. Along the way, you’ll learn how to:

  • Send sprites zooming around the screen with JavaScript animations
  • Cause exploding effects with a jQuery plugin
  • Use hitboxes and a bit of geometry to detect collisions
  • Implement game logic to display levels and respond to player input
  • Convey changes in game state through animation and sound
  • Add flair to a game interface with CSS transitions and transformations
  • Gain pixel-level control over the game display with the canvas

Hit the ground running as you start programming the bubble shooter from the very first chapter. Exercises at the end of each chapter test your new skills by challenging you to dig into the bubble shooter’s code and modify the game.

You can create a complete game right now, with skills that you already have. Let Build an HTML5 Game teach you the basics, and then transfer that knowledge to create any game you can imagine.

Get 40% off with the discount code BRIGHTANDEARLY if here:

A New Venture: Wedu Games

My new venture, Wedu Games, is up and running. Or at least the site is as there are no games finished yet. There are a few things in development, though, including an interactive storytelling table app (that isn’t a game at all) and a stud/hold-em poker hybrid to launch on mobile and Facebook together. Everything’s being built in HTML and JavaScript with possibly a bit of Node.js for simple back-end.

In the meantime there are a few blog posts to read. Now, back to making the games again…

Repeatable random numbers in JavaScript

Ever since programming BASIC on the Spectrum I’d wondered why it was possible to seed a “random” number generator. But then I found I wanted to do something that would produce repeatable results, but look like a random sequence. Strangely, although JavaScript alongs you to specify a seed for Math.random() the numbers that follow aren’t a repeated sequence. I’m guessing the system clock comes into it.

So after some Googling for an equation to generate numbers I put together the following function. It works on a sequence of 2^32 numbers, in “random” order. (I believed the equation I found – I didn’t test the completeness of it, but it looks pretty random to me.) So, just call to get a decimal between 0 and 1, or pass in a range (lower,upper) and you get a random number between the two.

var Random =
 seed : 12345,
 //Returns a random number between 0 and 1
 next : function(lower,upper)
  var maxi = Math.pow(2,32);
  this.seed = (134775813 * (this.seed + 1))
     % maxi;
  var num = (this.seed) / maxi;
  if(typeof lower!='undefined')
   var range = upper - lower;
   num *= range;
   num += lower;
  return num;

Set “Random.seed” to taste.

Firing JavaScript functions after a .Net AJAX request

I wanted to have a function called after data was returned to the page from a .Net AJAX call. (The idea was to fade out when you pressed “submit” and then redraw when data came back.) It turns out there are handy handlers already there to, erm, handle this:


Those little nuggets add calls to your functions, and the functions themselves are:

function StartRequestHandler(sender,args)
function EndRequestHandler(sender, args)


JavaScript solution to PNG alpha transparency in IE

Solutions to the problem of PNG alpha transparency in IE6 have been around for a while, as exemplified by this post on Cross-Browser Variable Opacity with PNG on A List Apart. This solution uses script to write in the correct html, or to pass variables to a script and set a property of an object. Other solutions involve using server-side browser sniffing to serve different CSS depending on the browser.

The crux of the problem is that IE6 doesn’t support the Alpha channel of PNG files used as an image. The solution is to take advantage of one of the proprietary DirectX filters built into Internet Explorer (for Windows) and to use this instead of the background image. The important point to note is that it is an ‘either/or’ solution – the PNG is used as a background image for the other browsers, and as a filter source in IE. Including both in IE means the PNG appears but with a nasty grey where all the transparency should be.

I’ve come up with the JavaScript below as an instant fix solution which means no rewriting of existing code is necessary. The CSS file will contain the background image as supported by Firefox and the other (non IE) modern browsers. (IE 7 is supposed to fix this, by the way.) The JavaScript runs through the stylesheet and replaces all of the background images with DirectX filters. The script should be placed in the head of the page just after the stylesheet tags and works automatically (although I haven’t yet tested it in older browsers).

You’ll need to remove some of the linebreaks which I’ve marked with a \n.

 var stylesheets=document.styleSheets;
 for(var i=0;i0)){

The way this works is to loop through each stylesheet, then each rule in the stylesheet, looking for any one with the backgroundImage property set. If it’s set it takes the image name from it (stripping out the url(”) bit) and sets that as the source of a DXImageTransform CSS filter. It then removes the backgroundImage property.

More JavaScript haiku

I first published a JavaScript haiku called ‘Fear of tomorrow’ here. Well, I’ve written some more. Apparently these are more likely to be classed as Senryuu, but what do I know. Anyway, here are some others that I’ve written, with the code first and the way it’s supposed to be read following it, and then an explanation of the ‘meaning’:

A baker’s dozen?

var i=1;

var i equals one
while i is less than 13
alert i plus plus

Although on the face of it just a script which displays numbers from 1 to 12, there is some ambiguity of meaning in the use of i++ which causes the reader to think and question whether the value of i will be alerted before being incremented or the other way round. It is, of course, alerted before being incremented but this moment of doubt reflects the author’s questioning of the logic behind the term “baker’s dozen” (being 13) and the discord it has with a ‘true’ dozen of 12 and the indecision as to which one to count up to.

The value of being together


i equals point 5
u equal math dot random
alert u plus i

This short piece raises questions of the value of two people joining together and whether the sum is greater or smaller than average. The first person (i) is an ‘average’ person and if the second person (u) is of above average value then the total will be greater than one. If not, then the value will be below one. This poem can be applied to anyone’s life and if you give yourself a score of 0.5 and then rate your partner accordingly the same equation can be used to determine whether you should dump them or not.

Eight days of sailing

var course="straight";

var course equals straight
navigator equals true
alert course dot length

A straightforward nautical tale where the navigator confirms that the voyage will consist of eight days of straight sailing.

More dubious works will doubtless follow…

Deleting page elements using removeChild in JavaScript

Here’s a handy(?) script to delete pieces of any page you’re on when you click on them:

javascript:document.onclick=new Function(‘e’,’document.all?;
src.parentNode.removeChild(src);return false’);void(0);

Go to any page on the web, paste it into the address bar of your browser and then start clicking around. It works okay in IE6 and Firefox – I haven’t tried it in anything else but it should be okay in IE5 (PC), and might work in Safari.

It uses JavaScript to access the DOM and then tells every element you click on to delete itself from its parent. Generally, a bit suicidal.

Try it out by clicking on this link and then clicking around on the page.