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') {
$.ajax({
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') {
$.ajax({
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'];
}
}
resolve();
},
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.