简体   繁体   English

电子自动更新窗口

[英]Electron Auto-update Windows

Can anyone help me with a description from scratch how to use auto-updater in electron. 任何人都可以从头开始为我提供一个如何在电子中使用自动更新程序的描述。 How to use the correct packages and write correct CLI to have a simple app that has auto-update in Windows. 如何使用正确的程序包并编写正确的CLI以使简单的应用程序在Windows中具有自动更新的功能。

Many thanks. 非常感谢。

I tried electron-basic-updater, electron-asar-updater, electron-installer-windows et al. 我尝试了electron-basic-updater, electron-asar-updater, electron-installer-windows等。 and spent hours trying out how to release/update my app, before settling with electron-packager for packaging and Squirrel for auto-updates. 并花了几个小时尝试如何发布/更新我的应用程序,然后再使用electron-packager进行打包,并使用Squirrel进行自动更新。 They have their advantages. 他们有自己的优势。

I am assuming the reader has a basic know-how of working with Electron apps and I'm hence not going into the basics. 我假设读者具有使用Electron应用程序的基本知识,因此我不介绍基础知识。

Important Note: You must create a package/installer in windows and install the app for auto-updater to work! 重要说明:您必须在Windows中创建一个程序包/安装程序,然后安装该应用程序,自动更新程序才能正常工作!

In you main app.js, add an IPC to handle the update scenario: 在您的主要app.js中,添加一个IPC来处理更新方案:

ipcMain.on('check-for-update', function(event, arg) {

/* AUTO UPDATER */
const autoUpdater = electron.autoUpdater;
const os = require('os');
const {dialog} = require('electron');

/* For Windows, PATH to DIRECTORY that has nupkg and RELEASES files (Windows alone) */
/* And add "Options Indexes" to htaccess if you want listing on that dir --@thinkdj */

var releaseDIR = config.webURL + '/releases/win' + (os.arch() === 'x64' ? '64' : '32');

autoUpdater.setFeedURL(releaseDIR);

autoUpdater
    .on('error', function(error){
        loggit(error);
        return dialog.showMessageBox(mainWindow, {
            type: 'info',
            icon: basePath + "/assets/refico32.ico",
            buttons: ['Dang!'],
            title: appName + ": Update Error",
            message: "Something's not right out there. Please try again later.",
            detail: "Umm... \nIt's not you, it's the server"
        });
    })
    .on('checking-for-update', function(e) {
        loggit('Checking for update at ' + releaseDIR);
    })
    .on('update-available', function(e) {

        var downloadConfirmation = dialog.showMessageBox(mainWindow, {
            type: 'info',
            icon: basePath + "/assets/refico32.ico",
            buttons: ['Proceed'],
            title: appName + ": Update Available",
            message: 'An update is available. The update will be downloaded in the background.',
            detail: "Size: ~42 MB"
        });

        loggit('Downloading update');

        if (downloadConfirmation === 0) {
            return;
        }

    })
    .on('update-not-available', function(e) {
        loggit('Update not available');
        return dialog.showMessageBox(mainWindow, {
            type: 'info',
            icon: basePath + "/assets/refico32.ico",
            buttons: ['Cool'],
            title: appName + ": No update available",
            message: "It seems you're running the latest and greatest version",
            detail: "Woot, woot! \nTalk about being tech-savvy"
        });
    })
    .on('update-downloaded',  function (event, releaseNotes, releaseName, releaseDate, updateUrl, quitAndUpdate) {

        var index = dialog.showMessageBox(mainWindow, {
            type: 'info',
            icon: basePath + "/assets/refico32.ico",
            buttons: ['Install Update','Later'],
            title: appName + ": Latest version downloaded",
            message: 'Please restart the app to apply the update',
            detail: releaseName + "\n\n" + releaseNotes
        });

        if (index === 1) return;

        force_quit = true;
        autoUpdater.quitAndInstall();
    });


autoUpdater.checkForUpdates();

event.returnValue = "Checking for updates: " + releaseDIR + " Install Path: " + appPath;
 });

Additional Notes: 1] Your app.js must handle squirrel events in the very beginning. 附加说明: 1]您的app.js必须从一开始就处理松鼠事件。 You can write your own handlers for handleSquirrelEvent or just a simple if (require('electron-squirrel-startup')) return; 您可以为handleSquirrelEvent编写自己的处理程序,也可以仅返回一个简单的if (require('electron-squirrel-startup')) return; would do. 会做。 2] At the time of writing this, once the process for auto-update has been initiated, there is no way for the user cancel the update process. 2]在撰写本文时,一旦启动了自动更新过程,用户将无法取消更新过程。

For creating your Installer, your Gruntfile.js (after npm install grunt, npm install grunt-cli ) should be something like 为了创建安装程序,您的Gruntfile.js(在npm install grunt, npm install grunt-cli )应该类似于

module.exports = function(grunt) {
    grunt.loadNpmTasks('grunt-electron-installer');
    grunt.initConfig({
        'create-windows-installer': {
        'ia32': {
            appDirectory: "C:\\refreshie\\app\\build\\Refreshie-win32-ia32",
            outputDirectory: "C:\\refreshie\\app\\build\\Distro\\Refreshie-Win-ia32",
            loadingGif: "C:\\refreshie\\app\\assets\\images\\install.splash.gif",
            iconUrl: "C:\\refreshie\\app\\assets\\refico.ico",
            setupIcon: "C:\\refreshie\\app\\assets\\refico.ico",
            signWithParams: "/a /f C:\\refreshie\\app\\build\\tools\\cert.signingkey.pfx /p F5",
            noMsi: true
        }
    }
    });
    grunt.registerTask('default', ['create-windows-installer']);
};

Currently, the best way to do electron auto-update is using electron-builder. 当前,执行电子自动更新的最佳方法是使用电子生成器。

npm install electron-builer –save-dev npm安装电子锅炉–save-dev

npm install electron-updater –save npm安装电子更新程序–save

For demo purpose, get http-server as you web host server. 出于演示目的,将http-server用作Web主机服务器。

npm install http-server –save npm安装http-server –save

Build package is very simple, create two folder "build" and "dist", then Add this in package.json script and run 构建包非常简单,创建两个文件夹“ build”和“ dist”,然后将其添加到package.json脚本中并运行

"scripts": {
   "start": "set NODE_ENV=dev&& tsc && concurrently \"npm run tsc:w\" \"electron .\" ",
   "tsc": "tsc",
   "tsc:w": "tsc -w",
     ;
   "dist": "build -w --x64",
   "wb": "http-server wwwroot/ -p 8080",
      ;
 },

npm run dist npm run dist

for auto updater, create a folder wwwroot and assume that is your web host server and to start your web site as: 对于自动更新程序,请创建一个文件夹wwwroot并假定它是您的Web主机服务器,并以以下方式启动您的网站:

npm run wb npm运行wb

copy verything from dist folder to wwwroot folder. 将内容从dist文件夹复制到wwwroot文件夹。

Ok done that. 好了

Please see here for full detail code 在此处查看完整的详细代码

Please follow the steps to achieve the electron js auto-update code working. 请按照以下步骤来实现electronic js自动更新代码的正常工作。

  1. npm install electron-updater (For using auto-updater) npm install electron-updater (用于使用自动更新程序)
  2. npm install electron-log (This will help to see the errors in logs) npm install electron-log (这将有助于查看日志中的错误)
  3. npm install electron --save-dev
  4. npm install electron-builder --save-dev

Then, in your main.js (the entry file of your application paste auto update code at as mentioned) 然后,在您的main.js中(您的应用程序的入口文件将自动更新代码粘贴到上述位置)

const electron = require('electron');
const url = require('url');
const path = require('path');
const pjson = require('../package.json')

// auto update code
const log = require('electron-log');
const { autoUpdater } = require("electron-updater");
autoUpdater.logger = log;
autoUpdater.logger.transports.file.level = 'info';
log.info('App starting...');
let appversion = pjson.version;

const { app, BrowserWindow } = electron;

let homePageWindow;

function sendStatusToWindow(text, ver) {
    log.info(text);
    homePageWindow.webContents.send('message', text, ver);
}

function createDefaultWindow() {
    homePageWindow = new BrowserWindow({
        minimizable: true,
        maximizable: true,
        closable: true,
    });
    homePageWindow.maximize();
    homePageWindow.webContents.openDevTools();
    //homePageWindow.setMenu(null);

    homePageWindow.on('closed', () => {
        homePageWindow = null;
        app.quit();
    });

    homePageWindow.loadURL(url.format({
        pathname: path.join(__dirname, '../webFiles/homePage.html'),
        protocol: 'file:',
        slashes: true


   }));
    return homePageWindow;
}

// auto update conditions
autoUpdater.on('checking-for-update', () => {
    sendStatusToWindow('Checking for update...', appversion);
})

autoUpdater.on('update-available', (info) => {
    sendStatusToWindow('Update available.', appversion);
})

autoUpdater.on('update-not-available', (info) => {
    sendStatusToWindow('Update not available.', appversion);
})

autoUpdater.on('error', (err) => {
    sendStatusToWindow('Error in auto-updater. ' + err, appversion);
})

autoUpdater.on('download-progress', (progressObj) => {
    let log_message = "Download speed: " + progressObj.bytesPerSecond;
    log_message = log_message + ' - Downloaded ' + progressObj.percent + '%';
    log_message = log_message + ' (' + progressObj.transferred + "/" + progressObj.total + ')';
    sendStatusToWindow(log_message, appversion);
})

autoUpdater.on('update-downloaded', (info) => {
    setTimeout(function () {
        sendStatusToWindow('Update downloaded..Restarting App in 5 seconds', appversion);
        homePageWindow.webContents.send('updateReady');
        autoUpdater.quitAndInstall();
    }, 5000)
});

app.on('ready', function () {
    createDefaultWindow();
    autoUpdater.checkForUpdatesAndNotify();
});

app.on('window-all-closed', () => {
    app.quit();
});

Refer to my code and do the needful changes in your main.js 请参阅我的代码,并在main.js中进行必要的更改

Then set the version of your application to say 1.0.0 Run command "npm run build --win -p always" to generate first build 然后将应用程序的版本设置为1.0.0,运行命令“ npm run build --win -p always”以生成第一个版本

I use Github to store the apps components. 我使用Github来存储应用程序组件。 So, you need to upload the app files of 1.0.0 (latest.yml, builder-effective-config.yaml, app_setup1.0.0.exe, app_setup1.0.0.exe.blockmap file) on git and create a release for it. 因此,您需要在git上载1.0.0的应用程序文件(latest.yml,builder-effective-config.yaml,app_setup1.0.0.exe,app_setup1.0.0.exe.blockmap文件)并为其创建发行版。 Publish the release as 1.0.0 将发布发布为1.0.0

Then change the version of the app to 1.0.1 Run command "npm run build --win -p always" to generate second build. 然后将应用程序的版本更改为1.0.1。运行命令“ npm run build --win -p always”以生成第二个版本。

Again do the github step - you need to upload the app files of 1.0.1 (latest.yml, builder-effective-config.yaml, app_setup1.0.1.exe, app_setup1.0.1.exe.blockmap file) on git and create a release for it. 再次执行github步骤-您需要在git上载1.0.1的应用程序文件(latest.yml,builder-effective-config.yaml,app_setup1.0.1.exe,app_setup1.0.1.exe.blockmap文件)。为此释放。 Publish the release as 1.0.1 将发布发布为1.0.1

So now in your project on git you have 2 releases 1.0.0 and 1.0.1 所以现在在您的git项目中,您有2个版本1.0.0和1.0.1

Now for testing the things you need to run the setup of 1.0.0 on your local machine. 现在,要测试事物,您需要在本地计算机上运行1.0.0的设置。 So, if the code is written correctly you will see logs that 1. Update available 2. Update downloaded and its % 因此,如果代码编写正确,您将看到以下日志:1.更新可用2.更新下载及其%

Then once 100% download is completed the app gets restarted in 5 seconds (as per seconds mentioned in the code) and your app is updated now. 然后,一旦100%下载完成,该应用程序将在5秒钟内重新启动(按照代码中提到的秒数),然后立即更新您的应用程序。 Yayyyyyyyyy Yayyyyyyyyy

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM