从Javascript检查Cordova版本

时间:2015-08-13 22:19:07

标签: javascript java cordova

有没有办法从Javascript查看正在运行的应用程序的Cordova版本?

为什么我问:

我们已将Cordova从2.8升级到4.0.2, Cordova JS文件无法与 Cordova Android代码一起使用。我们希望强制用户升级他们的应用程序(反过来更新他们的Cordova Android版本),但是,我们需要首先检测他们是旧版本。

为什么device.cordova不起作用:

似乎旧的Cordova JS代码从未初始化,因为它无法与新的Cordova Android代码进行通信。因此永远不会加载插件,例如设备插件。我们在控制台中收到一条消息:

deviceready has not fired after 5 seconds

2 个答案:

答案 0 :(得分:1)

EDIT:现在最简单的解决方案是:https://stackoverflow.com/a/65476892/1243247

手动方式

我制作了一个函数式挂钩脚本,并将其存储在 hooks/setVersion.js。我现在刚刚对其进行了测试并且可以正常工作(仅在 Android 中,对于 iOS,您只需要复制 wwwDir

#!/usr/bin/env node
var wwwFileToReplace = 'index.html'

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

module.exports = function (context) {
  var projectRoot = context.opts.projectRoot
  const wwwDir = path.join(projectRoot, 'platforms', 'android', 'app', 'src', 'main', 'assets', 'www')

  var configXMLPath = 'config.xml'
  loadConfigXMLDoc(configXMLPath, (rawJSON) => {
    var version = rawJSON.widget.$.version
    console.log('Version:', version)

    var fullfilename = path.join(wwwDir, wwwFileToReplace)
    if (fs.existsSync(fullfilename)) {
      replaceStringInFile(fullfilename, '%%VERSION%%', version)
      console.log(context.hook + ': Replaced version in file: ' + path.relative(projectRoot, fullfilename))
    } else {
      console.error('File does not exist: ', path.relative(projectRoot, fullfilename))
      process.exit(1)
    }
  })
}

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

function replaceStringInFile (filename, toReplace, replaceWith) {
  var data = fs.readFileSync(filename, 'utf8')

  var result = data.replace(new RegExp(toReplace, 'g'), replaceWith)
  fs.writeFileSync(filename, result, 'utf8')
}

您还必须在 config.xml 中添加

<hook src="hooks/setVersion.js" type="after_prepare"/>

此脚本将文件中的文本 %%VERSION%% 替换为 config.xml 中的应用程序版本,因此您可以在 index.html 文件中添加类似

<html data-appversion="%%VERSION%%">

在你的 JS 中

const version = document.documentElement.getAttribute("data-appversion");

答案 1 :(得分:0)

您可以使用device.cordova获取当前版本的Cordova。

Appropriate documentation