How to use preload.js properly in Electron

前端 未结 2 1236
不思量自难忘°
不思量自难忘° 2020-12-25 10:38

I\'m trying to use Node modules (in this example, fs) in my renderer processes, like this:

// main_window.js
const fs = require(\'f         


        
2条回答
  •  清酒与你
    2020-12-25 11:35

    Things have progressed quickly in Electron, causing some confusion. The latest idiomatic example (as best as I can determine after much gnashing of teeth) is:

    **main.js**
    
    
    app.whenReady().then(() => {`
        let mainWindow = new BrowserWindow({`
            nodeIntegration: false,
            contextIsolation: true,
            webPreferences: {
                preload: path.join(__dirname, 'preload.js'),
                contextIsolation: true
            },
            width:640,
            height: 480,
            resizable: false
        })
     ... rest of code
    
    
    **preload.js**
    
    const { contextBridge, ipcRenderer} = require('electron')
    
    contextBridge.exposeInMainWorld(
        'electron',
        {
            sendMessage: () => ipcRenderer.send('countdown-start')
        }
    )
    
    **renderer.js**
    
    document.getElementById('start').addEventListener('click', _ => {
        window.electron.sendMessage()
    })
    

提交回复
热议问题