电子:在BrowserWindow和呈现的URL之间进行通信(nodeIntegration:false)

ona*_*sar 4 javascript electron

在博客发布后的回购之后,我花了大约一个小时来阅读要点,但似乎无法弄清楚该如何做。

我有一个BrowserWindow实例,使用加载URL(由我控制)nodeIntegration: false

在主要过程中,我想与呈现的URL进行通信。我对preload脚本BrowserWindow.sendexecuteJavascript范例感到困惑。

我要发送的数据非常大(例如,文件上传介于50kb和10mb之间)。

最好的方法是什么?您可能知道的任何示例/教程都会有所帮助。谢谢!

fee*_*nda 7

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

const window = new BrowserWindow({
    minWidth: 1200,
    minHeight: 700,
    autoHideMenuBar: true,
    resizable: true,
    show: false,
    scrollBounce: true,
    webPreferences: {
    preload: path.join(__dirname, 'preload.js'),
  }
})
window.webContents.loadURL('https://xxx.xxx.com') // load your web page
ipcMain.on('ping', (event, msg) => {
   console.log(msg) // msg from web page
   window.webContents.send('pong', 'hi') // send to web page
})


// preload.js
const { ipcRenderer } = require('electron');
function init() {
    // add global variables to your web page
    window.isElectron = true
    window.ipcRenderer = ipcRenderer
}

init();


// your web page
<script>
  if (window.isElectron) {
      window.ipcRenderrer.send('ping', 'hello')
      window.ipcRenderrer.on('pong', (event, msg) => console.log(msg) )
  }
</script>
Run Code Online (Sandbox Code Playgroud)

  • 根据 [https://electronjs.org/docs/tutorial/security],这不被认为是安全的。在这里查看我的答案:/sf/answers/4035939701/ (3认同)