The hot update of Cordova is divided into two parts: the static content of the web page is updated and the cordova plug-in is updated. The static content of the web page is run based on Cordova. For example, the third-party login to QQ and wechat requires the integration of QQ and wechat plug-ins

Integrate update hot update plug-in

// Add a plug-in
cordova plugin add cordova-hot-code-push-plugin
// Install the hot Update tool globallyNPM or CNPM install -g cordova-hot-code-push-cli// Run a command in the root directory of cordova to add the cordova-hcp.json file, which is the template of the hot update file chcp.json
cordova-hcp init

Running init
Please provide: Enter project name (required):  cordovaVueDemo  // Project name
Please provide: Amazon S3 Bucket name (required for cordova-hcp deploy):  // Amazon S3 bucket name can be skipped
Please provide: Path in S3 bucket (optional for cordova-hcp deploy):  // S3 storage bucket path, which can be skipped
Please provide: Amazon S3 region (required for cordova-hcp deploy):  (us-east-1)  // Amazon S3 regions can be skipped
Please provide: IOS app identifier:  // The ID of the IOS App Store. An App upgrade is a jump to the App store to upgrade
Please provide: Android app identifier:  // Android App in the App store address, or App download address
Please provide: Update method (required):  (resume) start // The method to perform the update start(when starting the application) resume(when resuming the application, such as switching from the console to the foreground) now(install the update immediately after downloading)
Please provide: Enter full URL to directory where cordova-hcp build result will be uploaded:  http://xxxxxx.com/www // Address of the WWW resource file on the server
Project initialized and cordova-hcp.json file created.
If you wish to exclude files from being published, specify them in .chcpignore
Before you can push updates you need to run "cordova-hcp login" in project directory

// Add "autogenerated": true to cordova-hcp.json file
// The update will be invalid if you do not add it. The complete cordova-hcp.json file should look like this after the operation is complete
// Add iosMinVersion, androidVersion to control the App version, plug-in updates need to reinstall the App to take effect
{
  "name": "cordovaVueDemo"./ / can be null
  "autogenerated": true.// If not added, hot updates will not work
  "ios_identifier": "".// App store id(null)
  "android_identifier": "".// App store address or App download address (can be empty)
  "update": "start".// Install at application startup
  "content_url": "http://xxxxxx/cordova/www".// address of the WWW file on the server
  "iosMinVersion": "1.0.0".// For the ios version, use this to determine if you need to re-download the app. Usually, you need to change this when you update cordova
  "androidVersion": "1.0.0" // For The Android version, use this to determine if you need to re-download the app. Usually, you need to change this when you update cordova
  "updateLog": "Update log"
}
Copy the code

Generate chcp.json and chcp.mainfest files in the WWW folder

  • Json contains the cordova-hcp. Json template information, latest release information, resource time, and Native side version number

  • Chcp.mainfest contains hot update static file information (resource file name and hash value, which will be used to match the corresponding file to achieve accurate update).

// Run the command
cordova-hcp build
// After the command is executed, the "release":" current time "field is added to the template. This field is used to determine when an update is made
"release": "2021.06.17-16.30.20".// Unique Web project version number, used with hot update Web content updates. (required)
Copy the code

Config.xml configuration

// Add it somewhere below config.xml
<chcp>
    <config-file url="http://xxxxxx/cordova/www/chcp.json" /> // The path where the configuration file chcp.json is loaded from the server (required configuration items)
    <auto-download enabled="false" /> // Whether to download the update automatically, default is true, because I manually update the method, so set to false
    <auto-install enabled="false" /> // Whether to install the updates automatically. The default is true, because I manually update the method, so set it to false
    <native-interface version="1" /> // Native Side version number
</chcp> 
Copy the code

Hot update deployment

In this step, directly replace the files in the WWW folder on the server, Note that the WWW file in the service address must be with “content_URL “:”http://************/cordova/www” and config.xml
fill in the address is the same, this is the restart App, hot update should be able to perform normally, However, we set “auto-download” and “auto-install” to false, so the update does not automatically execute, so we will write the update logic next

Update logic editing

// I'm using the vue project, so I'll write it as vue
// Create the util.js file
class Util {
  // Configure the hot update service address
  chcpConfigure() {
    return new Promise((resolve, reject) = > {
      chcp.configure(
        { "config-file": process.env.VUE_APP_CHCP_SERVER },
        (err) = > {
          if (err) {
            Toast("Hot update address configuration error");
            reject();
          } else{ resolve(); }}); }); }// Get the hot update version number
  chcpGetVersion() {
    return new Promise((resolve, reject) = > {
      chcp.getVersionInfo((err, data) = > {
        if (err) {
          reject();
        } else{ resolve(data); }}); }); }// Check whether the server has been updated
  chcpFetchUpdate() {
    return new Promise((resolve, reject) = > {
      chcp.fetchUpdate((err, data) = > {
        if (err) {
          reject(err);
        } else{ resolve(data); }}); }); }// Install has downloaded the update
  chcpInstallUpdate() {
    return new Promise((resolve, reject) = > {
      chcp.installUpdate(err= > {
        if (err) {
          reject(err)
        } else{ resolve() } }); }}})export default new Util();

// Write the logic in the app.vue file
import util from "@/common/util";

export default {
  methods: {
    getAppChcpVersion() {
      util.chcpGetVersion().then((versionData) = > {
        this.checkedAppUpdate(versionData, 0);
      });
    },
    checkedAppUpdate(versionData, type) {
      // type 0 Automatic detection 1 manual update
      const self = this;
      // The getOnlineVersion function directly requests the CHCP. Json file of the online server WWW using the axios.get method
      getOnlineVersion().then((res) = > {
        let iosMinVersion = Number(res.iosMinVersion.replace(/\./g."")),
          androidVersion = Number(res.androidVersion.replace(/\./g."")),
          appVersion = Number(versionData.appVersion.replace(/\./g.""));
        // Determine whether increments are allowed or the full App must be downloaded
        if (
          (util.isAndroid() && appVersion < androidVersion) ||
          (util.isIos() && appVersion < iosMinVersion)
        ) {
          self.$dialog
            .alert({
              title: "Title".message: "Please go and download the full App.".theme: "round-button",
            })
            .then(() = > {
              window.location.href = "App Download Address";
            });
        } else {
          if(versionData.currentWebVersion ! = res.release) {// Determine whether to force the update
            if (res.updateType == 1) {
              self.$toast({
                message: "System forced update!!".onClose(){ self.checkedHasFetchUpdate(); }}); }else {
              self.$dialog
                .confirm({
                  title: "Software Update".message: res.updateLog,
                })
                .then(() = > {
                  self.checkedHasFetchUpdate();
                })
                .catch(() = >{}); }}}}); },checkedHasFetchUpdate() {
      this.$toast.loading({
        message: "Updating...".duration: 0}); util .chcpFetchUpdate() .then((data) = > {
          util
            .chcpInstallUpdate()
            .then(() = > {
              this.$toast("Update installed successfully");
            })
            .catch((err) = > {
              console.log(err);
              this.$toast("Update installation error");
            });
        })
        .catch((err) = > {
          console.log(err);
          this.$toast("Update pack obtaining failed"); }); }},created(){
    document.addEventListener(
      "deviceready".() = > {
        this.getAppChcpVersion();
      },
      false); }}// If there is no problem at this stage, the hot update will be executed normally. When you open the App, the method will be executed, and if there is an update, a prompt will be displayed asking for an update
Copy the code

Thermal renewal method

Method names The callback parameter instructions
chcp.isUpdateAvailableForInstallation (error, data) Determine if there are any downloaded updates available for installation
chcp.fetchUpdate (error, data) Obtain the version status of the server. If there is an update, download the update file
chcp.installUpdate (error) Install the downloaded updates

Thermal renewal event

The name of the event instructions
chcp_updateIsReadyToInstall The new version has been successfully downloaded and is ready to update
chcp_updateLoadFailed The plug-in could not get update data from the server
chcp_nothingToUpdate The plug-in gets the updated data configuration from the successful server, but no new version exists
chcp_beforeInstall Update before installation
chcp_updateInstalled Update after the installation is successful
chcp_updateInstallFailed Install update error
chcp_nothingToInstall No updates are installed; It is possible that the update was not downloaded first
chcp_beforeAssetsInstalledOnExternalStorage The plug-in is ready to download the updates to the store
chcp_assetsInstalledOnExternalStorage The plug-in successfully downloaded the update to the store
chcp_assetsInstallationError Error downloading update content of plug-in; The storage space may be insufficient

The error code

The error code Wrong name instructions
1 NOTHING_TO_INSTALL A request to install an update was sent, but no update was found
2 NOTHING_TO_UPDATE There are no updates
– 1 FAILED_TO_DOWNLOAD_APPLICATION_CONFIG Unable to download the updated configuration file from the server The configuration file may not exist or there is a network problem
2 – APPLICATION_BUILD_VERSION_TOO_LOW The client version is lower than update requirement. You need to download a new version of APK or IPA
– 3 FAILED_TO_DOWNLOAD_CONTENT_MANIFEST Error downloading update verification file. This may be caused by a configuration error of content_URL
4 – FAILED_TO_DOWNLOAD_UPDATE_FILES Check chcp.manifest. All files listed in chcp.manifest must be located on the server, and the check value of each file must be the same as that in chcp.manifest
– 5 FAILED_TO_MOVE_LOADED_FILES_TO_INSTALLATION_FOLDER An error occurred while moving the downloaded update file to the installation directory, possibly due to insufficient device space
– 6 UPDATE_IS_INVALID The downloaded update package is invalid. This may be because the downloaded file is inconsistent with the checksum in chcp.manifest
7 – FAILED_TO_COPY_FILES_FROM_PREVIOUS_RELEASE An error occurred while copying the WWW directory from the old version to the new version directory, possibly because of insufficient space on the device
– 8 – FAILED_TO_COPY_NEW_CONTENT_FILES Error copying the new file to the installation directory, possibly because there is not enough space on the device
9 – LOCAL_VERSION_OF_APPLICATION_CONFIG_NOT_FOUND An error occurred while reading the configuration file from the storage space. Procedure Possibly because the configuration file was manually deleted; The plug-in will read the last configuration
– 10 LOCAL_VERSION_OF_MANIFEST_NOT_FOUND Description An error occurred while reading the verification file from the storage space. Perhaps the validation file was manually deleted; The plug-in will read the last configuration
– 11 LOADED_VERSION_OF_APPLICATION_CONFIG_NOT_FOUND Error reading the new configuration file. Occurs during an installation update; The possible cause is that the file is manually deleted. This folder will be restored the next time the App runs
– 12 LOADED_VERSION_OF_MANIFEST_NOT_FOUND Error reading the validation file of the new version. Occurs during an installation update; The possible cause is that the file is manually deleted. This folder will be restored the next time the App runs
– 13 FAILED_TO_INSTALL_ASSETS_ON_EXTERNAL_STORAGE An error occurred while copying the WWW folder from the installation directory to the memory card. This may be due to insufficient storage space. Occurs when the application is first started; This error will cause the plug-in to fail to work properly
– 14 CANT_INSTALL_WHILE_DOWNLOAD_IN_PROGRESS The install update command was invoked during the download; You must wait for the download to complete before invoking the installation command
– 15 CANT_DOWNLOAD_UPDATE_WHILE_INSTALLATION_IN_PROGRESS The download update command was invoked during installation. You must wait until the installation is complete before you can invoke the download command
– 16 INSTALLATION_ALREADY_IN_PROGRESS The install command is invoked again during installation
– 17 DOWNLOAD_ALREADY_IN_PROGRESS The download command is called again during the download process
18 ASSETS_FOLDER_IN_NOT_YET_INSTALLED The CHCP hot update method was called when the plugin was copying the WWW file to storage when the application was first started