在我的Cordova应用程序中,如何获取我在config.xml中定义的版本字符串?

时间:2021-07-09 01:16:33

How do I find out, which version my Cordova app is? I need that information to display it in an About screen.

我怎么知道我的Cordova应用程序是哪个版本的?我需要该信息才能在“关于”屏幕中显示。

Is it possible to read the config.xml and get the version string, which i am already maintaining in this file?

是否可以读取config.xml并获取我已经在此文件中维护的版本字符串?

<widget ... version="0.0.1" ...

I would like to have a solution where i do not have to maintain the app's version number in several places in the code. Also I do not want a plugin for that purpose, because most plugins do not support Android, iOS and browser as platforms.

我想有一个解决方案,我不必在代码中的几个地方维护应用程序的版本号。此外,我不想为此目的插件,因为大多数插件不支持Android,iOS和浏览器作为平台。

Or am i overlooking a core plugin attribute?

或者我是否会忽略核心插件属性?

Or is there a solution where i maintain one file, which is no the config.xml, and the config.xml gets the version information from that file?

或者有一个解决方案,我维护一个文件,这不是config.xml,并且config.xml从该文件获取版本信息?

How are you implementing "display version info" in your app's about screen? Any hint is appreciated.

您是如何在应用程序的屏幕上实现“显示版本信息”的?任何提示都表示赞赏。

My Cordova version is:

我的Cordova版本是:

>cordova -v
4.2.0

4 个解决方案

#1


12  

If you are not interested in using any third party plugin to achieve this, then I feel Cordova hooks is the way to go. You can come up with a before_build hook to read the version from config.xml file and make use of the same in app.

如果你对使用任何第三方插件不感兴趣,那么我觉得Cordova钩子是要走的路。你可以提出一个before_build钩子来读取config.xml文件中的版本,并在app中使用相同的版本。

Fortunately, this hook is readily available for you in the following link where they are reading version from config.xml and injecting it as a dependency wherever required.

幸运的是,这个钩子在以下链接中随时可用,它们从config.xml读取版本并在需要时将其作为依赖项注入。

Suggest you to also have a look at the official documentation of cordova hooks for better understanding.

建议您也查看cordova挂钩的官方文档,以便更好地理解。

Infact, you can also try out reading version info from config.xml and directly put it in some placeholder that you can create in your index.html to display the version info. This can be done before cordova build using hooks which in turn uses windows batch file that does the file operations. You can checkout a working sample of cordova hook that uses batch file in my github page.

事实上,您还可以尝试从config.xml读取版本信息,并直接将其放在您可以在index.html中创建的某个占位符中以显示版本信息。这可以在使用钩子进行cordova构建之前完成,而钩子又使用执行文件操作的Windows批处理文件。您可以在我的github页面中查看使用批处理文件的cordova钩子的工作示例。

#2


2  

Based on the script that @Gandhi pointed to in his answer, I updated the script to make it work for me with the current cordova@8: I use it as "after_prepare" hook, not "before_build", as in the later case the changed file got overwritten again when cordova copied the stuff to the platform directory soon after the hook has been executed ...

基于@Gandhi在他的回答中指出的脚本,我更新了脚本以使其适用于我当前的cordova @ 8:我将它用作“after_prepare”钩子,而不是“before_build”,如在后一种情况下在执行挂钩后不久,当cordova将内容复制到平台目录时,更改的文件再次被覆盖...

The script uses xml2js, so be sure to exec npm i xml2js --save-dev to make xml2js available.

该脚本使用xml2js,因此请务必执行npm i xml2js --save-dev以使xml2js可用。

#!/usr/bin/env node

// taken from https://www.bram.us/2015/01/04/cordova-build-hook-script-for-displaying-build-version-in-your-app/
// see https://*.com/a/42650842
// This plugin replaces text in a file with the app version from config.xml.

// be sure to exec `npm i xml2js --save-dev` to make xml2js available


var wwwFileToReplace = "js/config.js";

var fs = require('fs');
var path = require('path');
var xml2js = require('xml2js');

function loadConfigXMLDoc(filePath) {
    var json = "";
    try {
        var fileData = fs.readFileSync(filePath, 'ascii');
        var parser = new xml2js.Parser();
        parser.parseString(fileData.substring(0, fileData.length), function (err, result) {
                           //console.log("config.xml as JSON", JSON.stringify(result, null, 2));
                           json = result;
                           });
        console.log("File '" + filePath + "' was successfully read.");
        return json;
    } catch (ex) {
        console.log(ex)
    }
}

function replace_string_in_file(filename, to_replace, replace_with) {
    var data = fs.readFileSync(filename, 'utf8');

    var result = data.replace(new RegExp(to_replace, "g"), replace_with);
    fs.writeFileSync(filename, result, 'utf8');
    //console.log("replaced in ", filename, "(", to_replace, " -> ", replace_with);
    var data2 = fs.readFileSync(filename, 'utf8');
    console.log(data2);
}

module.exports = function(context) {

    // var rootdir = process.argv[2]; // old cordova version
    var rootdir = context.opts.projectRoot;
    console.log("projectRoot=", rootdir);

    var configXMLPath = "config.xml";
    var rawJSON = loadConfigXMLDoc(configXMLPath);
    var version = rawJSON.widget.$.version;
    console.log("Version:", version);

    // var currentBuildPlatforms = process.env.CORDOVA_PLATFORMS.split(","); // old cordova version
    var currentBuildPlatforms = context.opts.cordova.platforms;
    //console.log(JSON.stringify(context));
    console.log("Current build platforms: ", currentBuildPlatforms);

    if (rootdir) {
        currentBuildPlatforms.forEach(function(val, index, array) {
            var wwwPath = "";
            switch(val) {
                case "ios":
                    wwwPath = "platforms/ios/www/";
                    break;
                case "android":
                    wwwPath = "platforms/android/assets/www/";
                    break;
                default:
                    console.log("Unknown build platform: " + val);
            }
            var fullfilename = path.join(rootdir, wwwPath + wwwFileToReplace);
            if (fs.existsSync(fullfilename)) {
                replace_string_in_file(fullfilename, "%%VERSION%%", version);
                console.log("Replaced version in file: " + fullfilename);
            }
        });
    }

}

Include this hook in your config.xml:

在config.xml中包含此挂钩:

<hook src="scripts/after_prepare_read_app_version.js" type="after_prepare" />

#3


1  

i use the plugin describe at https://github.com/whiteoctober/cordova-plugin-app-version 1 step : cordova plugin add https://github.com/whiteoctober/cordova-plugin-app-version.git

我使用插件描述在https://github.com/whiteoctober/cordova-plugin-app-version 1步骤:cordova插件添加https://github.com/whiteoctober/cordova-plugin-app-version.git

2 step (cut and paste) If you are using jQuery or AngularJS, promise style is supported. Use something like:

2步(剪切和粘贴)如果您使用的是jQuery或AngularJS,则支持promise样式。使用类似的东西:

cordova.getAppVersion.getVersionNumber().then(function (version) {
    $('.version').text(version);
});

If not, pass a callback function:

如果没有,则传递回调函数:

cordova.getAppVersion.getVersionNumber(function (version) {

alert(version);
});

cheers

干杯

#4


1  

I would just do something like this:

我会做这样的事情:

cordova.getAppVersion.getVersionNumber().then(function (version) {
   if (!window.localStorage['version'] || window.localStorage['version'] <    version) {
       window.localStorage['version'] = version;
   }
});

That way you can call window.localStorage['version'] where ever you need it.

这样你可以在任何需要的地方调用window.localStorage ['version']。

#1


12  

If you are not interested in using any third party plugin to achieve this, then I feel Cordova hooks is the way to go. You can come up with a before_build hook to read the version from config.xml file and make use of the same in app.

如果你对使用任何第三方插件不感兴趣,那么我觉得Cordova钩子是要走的路。你可以提出一个before_build钩子来读取config.xml文件中的版本,并在app中使用相同的版本。

Fortunately, this hook is readily available for you in the following link where they are reading version from config.xml and injecting it as a dependency wherever required.

幸运的是,这个钩子在以下链接中随时可用,它们从config.xml读取版本并在需要时将其作为依赖项注入。

Suggest you to also have a look at the official documentation of cordova hooks for better understanding.

建议您也查看cordova挂钩的官方文档,以便更好地理解。

Infact, you can also try out reading version info from config.xml and directly put it in some placeholder that you can create in your index.html to display the version info. This can be done before cordova build using hooks which in turn uses windows batch file that does the file operations. You can checkout a working sample of cordova hook that uses batch file in my github page.

事实上,您还可以尝试从config.xml读取版本信息,并直接将其放在您可以在index.html中创建的某个占位符中以显示版本信息。这可以在使用钩子进行cordova构建之前完成,而钩子又使用执行文件操作的Windows批处理文件。您可以在我的github页面中查看使用批处理文件的cordova钩子的工作示例。

#2


2  

Based on the script that @Gandhi pointed to in his answer, I updated the script to make it work for me with the current cordova@8: I use it as "after_prepare" hook, not "before_build", as in the later case the changed file got overwritten again when cordova copied the stuff to the platform directory soon after the hook has been executed ...

基于@Gandhi在他的回答中指出的脚本,我更新了脚本以使其适用于我当前的cordova @ 8:我将它用作“after_prepare”钩子,而不是“before_build”,如在后一种情况下在执行挂钩后不久,当cordova将内容复制到平台目录时,更改的文件再次被覆盖...

The script uses xml2js, so be sure to exec npm i xml2js --save-dev to make xml2js available.

该脚本使用xml2js,因此请务必执行npm i xml2js --save-dev以使xml2js可用。

#!/usr/bin/env node

// taken from https://www.bram.us/2015/01/04/cordova-build-hook-script-for-displaying-build-version-in-your-app/
// see https://*.com/a/42650842
// This plugin replaces text in a file with the app version from config.xml.

// be sure to exec `npm i xml2js --save-dev` to make xml2js available


var wwwFileToReplace = "js/config.js";

var fs = require('fs');
var path = require('path');
var xml2js = require('xml2js');

function loadConfigXMLDoc(filePath) {
    var json = "";
    try {
        var fileData = fs.readFileSync(filePath, 'ascii');
        var parser = new xml2js.Parser();
        parser.parseString(fileData.substring(0, fileData.length), function (err, result) {
                           //console.log("config.xml as JSON", JSON.stringify(result, null, 2));
                           json = result;
                           });
        console.log("File '" + filePath + "' was successfully read.");
        return json;
    } catch (ex) {
        console.log(ex)
    }
}

function replace_string_in_file(filename, to_replace, replace_with) {
    var data = fs.readFileSync(filename, 'utf8');

    var result = data.replace(new RegExp(to_replace, "g"), replace_with);
    fs.writeFileSync(filename, result, 'utf8');
    //console.log("replaced in ", filename, "(", to_replace, " -> ", replace_with);
    var data2 = fs.readFileSync(filename, 'utf8');
    console.log(data2);
}

module.exports = function(context) {

    // var rootdir = process.argv[2]; // old cordova version
    var rootdir = context.opts.projectRoot;
    console.log("projectRoot=", rootdir);

    var configXMLPath = "config.xml";
    var rawJSON = loadConfigXMLDoc(configXMLPath);
    var version = rawJSON.widget.$.version;
    console.log("Version:", version);

    // var currentBuildPlatforms = process.env.CORDOVA_PLATFORMS.split(","); // old cordova version
    var currentBuildPlatforms = context.opts.cordova.platforms;
    //console.log(JSON.stringify(context));
    console.log("Current build platforms: ", currentBuildPlatforms);

    if (rootdir) {
        currentBuildPlatforms.forEach(function(val, index, array) {
            var wwwPath = "";
            switch(val) {
                case "ios":
                    wwwPath = "platforms/ios/www/";
                    break;
                case "android":
                    wwwPath = "platforms/android/assets/www/";
                    break;
                default:
                    console.log("Unknown build platform: " + val);
            }
            var fullfilename = path.join(rootdir, wwwPath + wwwFileToReplace);
            if (fs.existsSync(fullfilename)) {
                replace_string_in_file(fullfilename, "%%VERSION%%", version);
                console.log("Replaced version in file: " + fullfilename);
            }
        });
    }

}

Include this hook in your config.xml:

在config.xml中包含此挂钩:

<hook src="scripts/after_prepare_read_app_version.js" type="after_prepare" />

#3


1  

i use the plugin describe at https://github.com/whiteoctober/cordova-plugin-app-version 1 step : cordova plugin add https://github.com/whiteoctober/cordova-plugin-app-version.git

我使用插件描述在https://github.com/whiteoctober/cordova-plugin-app-version 1步骤:cordova插件添加https://github.com/whiteoctober/cordova-plugin-app-version.git

2 step (cut and paste) If you are using jQuery or AngularJS, promise style is supported. Use something like:

2步(剪切和粘贴)如果您使用的是jQuery或AngularJS,则支持promise样式。使用类似的东西:

cordova.getAppVersion.getVersionNumber().then(function (version) {
    $('.version').text(version);
});

If not, pass a callback function:

如果没有,则传递回调函数:

cordova.getAppVersion.getVersionNumber(function (version) {

alert(version);
});

cheers

干杯

#4


1  

I would just do something like this:

我会做这样的事情:

cordova.getAppVersion.getVersionNumber().then(function (version) {
   if (!window.localStorage['version'] || window.localStorage['version'] <    version) {
       window.localStorage['version'] = version;
   }
});

That way you can call window.localStorage['version'] where ever you need it.

这样你可以在任何需要的地方调用window.localStorage ['version']。