Электрон, Создание дубликата главного окна при нажатии кнопки - PullRequest
0 голосов
/ 03 марта 2020

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

Я бы хотел, чтобы они могли это сделать, просто нажав кнопку внутри index.html.

Как это было бы возможно в следующем коде приложений по умолчанию?

main.js

const { app, BrowserWindow } = require('electron')

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

  // and load the index.html of the app.
  win.loadFile('index.html')

  // Open the DevTools.
  win.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.whenReady().then(createWindow)

// Quit when all windows are closed.
app.on('window-all-closed', () => {
  // On macOS 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 macOS 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 require them here.

index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Hello World!</title>
    <!-- https://electronjs.org/docs/tutorial/security#csp-meta-tag -->
    <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />
  </head>
  <body>
    <button onclick="openWindow()">click to open new window</button>
  </body>
</html>

Ответы [ 2 ]

1 голос
/ 03 марта 2020

Вы можете достичь своей цели двумя способами.

Вы должны изменить свой index.html на такой, как предварительные требования. На вашем index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Hello World!</title>
  </head>
  <body>
    <h1>Hello World!</h1>
    <body>
    <button onclick="require('./renderer.js').openWindow()">click to open new window</button>
  </body>
    <!-- All of the Node.js APIs are available in this renderer process. -->
    We are using Node.js <script>document.write(process.versions.node)</script>,
    Chromium <script>document.write(process.versions.chrome)</script>,
    and Electron <script>document.write(process.versions.electron)</script>.

    <script>
      // You can also require other files to run in this process
      require('./renderer.js')
    </script>
  </body>
</html>
  1. Использование ip c Общение.

На вашем main.js

const {app, BrowserWindow, ipcMain} = require('electron')
let browserWindows = [];

function createWindow () {
  // Create the browser window.
  let newWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true
    }
  })

  newWindow.loadFile('index.html')


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

  browserWindows.push(newWindow)
}

app.on('ready', createWindow)

// Quit when all windows are closed.
app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

ipcMain.on('createNewWindow', (evnet, args) => {
  createWindow();
})

На вашем renderer.js

const { ipcRenderer } = require('electron')
module.exports.openWindow = event => {
  ipcRenderer.send('createNewWindow', {});
}
Не используется IP c. Вы можете создать напрямую. Создайте browserWindow прямо у вашего рендерера без ipc Communitaion. Следовательно, вы активируете узел api у вашего рендерера Так что

На вашем renderer.js

const {BrowserWindow} = require('electron').remote
module.exports.openWindow = event => {
  const newWindow = new BrowserWindow({
      width: 800,
      height: 600,
      webPreferences: {
        nodeIntegration: true
      }
    })

  // and load the index.html of the app.
  newWindow.loadFile('index.html')
}

Таким образом, вам не нужно менять main.js

1 голос
/ 03 марта 2020

Все, что вам нужно сделать, это отправить сообщение вашему основному процессу, когда вы нажмете кнопку, затем в main.js создайте новое окно всякий раз, когда мы получим это сообщение.

Поэтому сначала отправьте сообщение main.js из вашей openWindow() функции следующим образом:

var ipcRenderer = require('electron').ipcRenderer;
function openWindow () {
    ipcRenderer.send('asynchronous-message', 'createNewWindow');
}

Затем мы слушаем сообщение в main.js, например:

var ipcMain = require('electron').ipcMain;
ipcMain.on('asynchronous-message', function (evt, message) {
    if (message == 'createNewWindow') {
        // Message received.
        // Create new window here.
    }
});

Затем все, что вам нужно сделать, это создать новое окно при получении сообщения 'createNewWindow'.

См. документы для отправки сообщения в основной процесс

См. документы для получения сообщений в основной процесс

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...