Passing Data to Windows in Electron

前端 未结 2 1304
挽巷
挽巷 2021-02-01 01:40

I\'m learning Electron and working with multiple windows and IPC. In my main script I have the following:

var storeWindow = new BrowserWindow({
  width: 400,
  h         


        
2条回答
  •  青春惊慌失措
    2021-02-01 02:09

    You need the ipcMain module to achieve this... As stated in the API "When used in the main process, it handles asynchronous and synchronous messages sent from a renderer process (web page). Messages sent from a renderer will be emitted to this module."

    API Docs for the ipcMain module: https://electronjs.org/docs/api/ipc-main

    To use the ipcMain you need to have nodeIntegration enabled on webPreferences

    win = new BrowserWindow({
        webPreferences: {
            nodeIntegration: true,
        }
    })
    

    Be careful this may cause security issues.

    For example: Let's say we want to pass a configuration (json) file to the web page

    (Triple dots (...) represent your code that is already placed inside the file, but is not relevant to this example)

    main.js

    ...
    
    const { readFileSync } = require('fs') // used to read files
    const { ipcMain } = require('electron') // used to communicate asynchronously from the main process to renderer processes.
    ...
    
    // function to read from a json file
    function readConfig () {
      const data = readFileSync('./package.json', 'utf8')
      return data
    }
    
    ...
    // this is the event listener that will respond when we will request it in the web page
    ipcMain.on('synchronous-message', (event, arg) => {
      console.log(arg)
      event.returnValue = readConfig()
    })
    ...
    

    index.html

    ...    
    
    

    To see the console of the browser you need to open the dev tools, either from the default Electron menu or from your code. e.g. inside the createWindow() function

     win.webContents.openDevTools()
    

提交回复
热议问题