本文介绍了电子:在BrowserWindow和呈现的URL之间进行通信(nodeIntegration:false)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

回写博客文章后,我已经花了大约一个小时来阅读要点,但是似乎无法弄清楚该怎么做.

I've spent about an hour reading gist after repo after blog post, but can't seem to figure out how to do do this.

我有一个 BrowserWindow 实例,该实例加载一个URL(由我控制),并带有 nodeIntegration:false .

I have a BrowserWindow instance loading a URL (that I control), with nodeIntegration: false.

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

From the main process, I'd like to communicate with the rendered URL. I'm getting confused between preload scripts, BrowserWindow.send and executeJavascript paradigms.

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

The data I want to send is very large (eg. file uploads between 50kb and 10mb).

执行此操作的最佳方法是什么?您可能知道的任何示例/教程都将有所帮助.谢谢!

What's the best way to do this? Any any examples/tutorials you may know about would be helpful. Thanks!

推荐答案

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 web page') // send to web page
})

preload.js

preload.js

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

init();

您的网页

<script>
  if (window.isElectron) {
    window.ipcRenderer.send('ping', 'hello main')
    window.ipcRenderer.on('pong', (event, msg) => console.log(msg))
  }
</script>

这篇关于电子:在BrowserWindow和呈现的URL之间进行通信(nodeIntegration:false)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-19 06:44