Электронная стрелочная функция showOpenDialog (event.send) не работает

Я следую примеру диалога для открытия файлов из: https://github.com/electron/electron-api-demos

Я скопировал код из примера. Диалог открытия файла действительно работает, и я могу выбрать файл, но не могу понять, почему функция стрелки для отправки пути к файлу обратно в средство визуализации не работает (в console.log ничего не регистрируется).

Кто-нибудь может заметить, что не так? Проект был запущен с помощью electronic-forge, а моя ОС - Linux. Спасибо

index.js

const { app, BrowserWindow, ipcMain, dialog, } = require('electron');
require('electron-reload')(__dirname);
const path = require('path');

// Handle creating/removing shortcuts on Windows when installing/uninstalling.
if (require('electron-squirrel-startup')) { // eslint-disable-line global-require
  app.quit();
}


const createWindow = () => {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true
    }
  });

  // and load the index.html of the app.
  mainWindow.loadFile(path.join(__dirname, 'index.html'));

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

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow);

// Quit when all windows are closed.
app.on('window-all-closed', () => {
  // On OS X it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', () => {
  // 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 (BrowserWindow.getAllWindows().length === 0) {
    createWindow();
  }
});

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and import them here.


ipcMain.on('open-file-dialog', (event) => {
  dialog.showOpenDialog(
    {
      properties: ['openFile',]
    },
    (files) => {
      console.log('ok')
      if (files) {
        event.sender.send('select-file', files)
      }
    })
})

index.html

<!DOCTYPE html>
<html>

<head>
  <title>Hello</title>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

</head>

<body>
  <div>
    <div>
      <button class="demo-button" id="select-directory">Select file</button>
      <span class="demo-response" id="selected-file"></span>
    </div>
    <br><br>
  </div>
  <script>
    const electron = require('electron')
    const { ipcRenderer } = electron

    const selectDirBtn = document.getElementById('select-directory')

    selectDirBtn.addEventListener('click', (event) => {
      ipcRenderer.send('open-file-dialog')
    })

    ipcRenderer.on('select-file', (event, path) => {
      console.log(path)
      document.getElementById('selected-file').innerHTML = `You selected: ${path}`
    })

  </script>
</body>

</html>

person kbsol    schedule 12.02.2020    source источник
comment
API диалогового окна изменился в Electron 6. См. stackoverflow.com/questions/59698444/   -  person snwflk    schedule 12.02.2020
comment
В демо-версиях Electron по-прежнему используется Electron 5.   -  person snwflk    schedule 12.02.2020
comment
Спасибо. Я не ожидал, что демо окажется настолько устаревшим. Пользуюсь версией 8!   -  person kbsol    schedule 12.02.2020


Ответы (1)


dialog API был изменен с выпуском Electron 6.

dialog.showOpenDialog() и другие функции диалогов теперь возвращают обещания и больше не принимают функции обратного вызова. Также существуют синхронные аналоги, которые возвращают результат выбора блокирующим образом, например dialog.showOpenDialogSync().

Пример использования (в процессе рендеринга)

const remote = require("electron").remote
const dialog = remote.dialog

dialog.showOpenDialog(remote.getCurrentWindow(), {
    properties: ["openFile", "multiSelections"]
}).then(result => {
    if (result.canceled === false) {
        console.log("Selected file paths:")
        console.log(result.filePaths)
    }
}).catch(err => {
    console.log(err)
})

По состоянию на февраль 2020 года electron-api-demos используют Electron 5. Вот почему их код вызова диалогового окна по-прежнему использует старую форму.

person snwflk    schedule 12.02.2020