электронное автообновление при нажатии - PullRequest
0 голосов
/ 18 ноября 2018

Я пытаюсь сделать мое электронное приложение автоматически обновляемым, и после поиска в Google я нашел хорошее руководство, которое работает.Единственная проблема заключается в том, что я хочу создать кнопку для загрузки обновления, чтобы пользователь мог решить, когда он хочет обновить и перезапустить приложение.До сих пор я был в состоянии собрать этот код вместе

renderer.js

const electron = require('electron')
const ipcRenderer = electron.ipcRenderer

let lastMsgId = 0

window.quitAndInstall = function () {
  electron.remote.autoUpdater.quitAndInstall()
}

ipcRenderer.on('console', (event, consoleMsg) => {
  console.log(consoleMsg)
})

ipcRenderer.on('message', (event, data) => {
  showMessage(data.msg, data.hide, data.replaceAll)
})

function showMessage(message, hide = true, replaceAll = false) {
  const messagesContainer = document.querySelector('.messages-container')
  const msgId = lastMsgId++ + 1
  const msgTemplate = `<div id="${msgId}" class="alert alert-info alert-info-message animated fadeIn">${message}</div>`

  if (replaceAll) {
    messagesContainer.innerHTML = msgTemplate
  } else {
    messagesContainer.insertAdjacentHTML('afterbegin', msgTemplate)
  }

  if (hide) {
    setTimeout(() => {
      const msgEl = document.getElementById(msgId)
      msgEl.classList.remove('fadeIn')
      msgEl.classList.add('fadeOut')
    }, 4000)
  }
}

, и это мой index.js, где хранятся сообщения

const electron = require('electron');
const {autoUpdater} = require('electron-updater');
const log = require('electron-log');
const appVersion = require('./package.json').version

// configure logging
autoUpdater.logger = log;
autoUpdater.logger.transports.file.level = 'info';
log.info('App starting...');

const app = electron.app;
const BrowserWindow = electron.BrowserWindow;

let mainWindow;

function createWindow() {
  mainWindow = new BrowserWindow({
    width: 1020,
    height: 800,
  });
  mainWindow.loadURL('file://' +__dirname + '/public/index.html');

  // Open the DevTools.
  //mainWindow.webContents.openDevTools();

  mainWindow.on('closed', function() {
    mainWindow = null;
  });
}

app.on('ready', createWindow);

// Quit when all windows are closed.
app.on('window-all-closed', function() {
    app.quit();
});

app.on('activate', function() {
  // On OS X it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (mainWindow === null) {
    createWindow();
  }
});

//-------------------------------------------------------------------
// Auto updates
//-------------------------------------------------------------------
const sendStatusToWindow = (text) => {
  log.info(text);
  if (mainWindow) {
    mainWindow.webContents.send('console', `App version: ${appVersion}`)
    mainWindow.webContents.send('message', { msg: `App version: ${appVersion}` })
  }
};

autoUpdater.on('error', (ev, err) => {
  mainWindow.webContents.send('message', { msg: `Error: ${err}` })
})

autoUpdater.once('checking-for-update', (ev, err) => {
  mainWindow.webContents.send('message', { msg: 'Checking for updates' })
})

autoUpdater.once('update-available', (ev, err) => {
  mainWindow.webContents.send('message', { msg: 'Update available. Downloading ⌛️', hide: false })
})

autoUpdater.once('update-not-available', (ev, err) => {
  mainWindow.webContents.send('message', { msg: 'Update not available' })
})

autoUpdater.once('update-downloaded', (ev, err) => {
  const msg = 'Update downloaded - <button onclick="quitAndInstall()">Restart</button>'
  mainWindow.webContents.send('message', { msg, hide: false, replaceAll: true })
})

autoUpdater.checkForUpdates()

Как выМожно видеть, что я добавил кнопку для вызова функции, но она не работает.Когда я нажимаю кнопку ничего не происходит.Если я удаляю кнопку и просто говорю auto.updater.quitAndInstall (), это работает.Это автоматически закрыть окно и установить новую версию.Чего мне не хватает?

1 Ответ

0 голосов
/ 20 ноября 2018

Я думаю, что electron.remote.autoUpdater.quitAndInstall() не работает при запуске в рендере.

В документации ничего не сказано против запуска в процессе рендерера, но я думаю, что отправка сообщения обратноосновной процесс для запуска функции quitAndInstall будет работать.

Внутри функции quitAndInstall вместо этого укажите:

ipcRenderer.send('asynchronous-message', 'quitAndInstall');

Затем в основном процессе поместите:

electron.ipcMain.on('asynchronous-message', function (evt, message) {
    if (message == 'quitAndInstall') {
        autoUpdater.quitAndInstall();
    }
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...