MainWindow не получает данные в electron js

#javascript #node.js #electron #electron-forge

#javascript #node.js #electron #electron-forge

Вопрос:

Итак, я создавал приложение todo с использованием electron js.Я хотел отправить задачи после загрузки окна, поэтому я использовал

main.js

 'use strict'

const { app, BrowserWindow } = require('electron');
const path = require('path');
const DataStore  = require('./DataStore');
const { ipcMain } = require('electron');

const todosData = new DataStore({ 'name':'Todo Mains'});
// 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();

  console.log(todosData.todos)

  mainWindow.once('dom-ready', () => {
    console.log('Dom is ready')
    mainWindow.webContents.send('todos',todosData.todos)
  });

};

// 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, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd   Q.
app.on('window-all-closed', () => {
  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.
`
  

index.html

 <script>
    const { ipcRenderer } = require('electron')
    
    ipcRenderer.on('todos',(event,todos) => {
      const todoList = document.getElementById('todo-Lists')
      if(!todoList){
        console.log('not there')
      }
      else{
        console.log(todoList)
        console.log('there')
      }
      const todoItems = todos.reduce((html,todo) => {
        html  = "<li id='todo-items'>${todo}</li>"
        return html
      },'')

      todoList.innerHTML = todoItems()
    })
  
  </script>
  </html>

  

итак, теперь, когда dom загружается, он должен правильно отображать задачи?но это происходит.
когда я использовал console.log (todosData.todos) в main.js он регистрирует задачи из файла json в терминал, но он не регистрирует журнал при входе из index.html .Это показывает, что данные, которые передаются из main.js для index.html .Итак, кто-нибудь может мне помочь с этим?

Комментарии:

1. Итак, вы говорите, что ни «не там», ни «там» нет в журналах окна браузера?

2. main.js логи в терминале правильно? и HTML-страница регистрируется в окне браузера. Итак, войдя в main.js он регистрируется в терминале, но не отображается в консоли окна браузера в инструментах разработчика. Это означает только то, что данные не передаются из main.js для index.html

3. Я никогда не сталкивался с какой-либо проблемой с таким механизмом. Можете ли вы, пожалуйста, убедиться, что ipcRenderer событие зарегистрировано ДО готовности содержимого dom и что оно эффективно зарегистрировано и что в консоли браузера не отображаются журналы?

4. Я добавил оператор импорта в саму первую строку. const { ipcRenderer } = требовать(‘electron’). Я отправлю всю кодовую страницу main.js

Ответ №1:

   mainWindow.webContents.once('dom-ready', () => {
    console.log('Dom is ready')
    mainWindow.webContents.send('todos',todosData.todos)
  });
  

В BrowserWindow нет dom-ready события. Это событие на webContents