繁体   English   中英

有没有办法将数据从 Electron 传递到 webview 中的 URL?

[英]Is there a way to pass data from Electron to the URL in the webview?

我有一个 Electron 应用程序,应用程序内部有一个 webview 来加载我的应用程序 UI。 出于某种原因,我需要将 Electron 框架和 UI 分开并作为两个应用程序运行。 UI 位于云端,Electron 使用 webview 来显示 UI。

我的 UI 需要来自 Electron 的一段数据才能继续运行,所以我正在寻找一种方法,要么 Electron 可以发出信号,然后 UI 可以执行诸如 addEventListener 之类的操作来等待信号,或者 UI 可以以某种方式访问Electron 检查该数据是否不为空。

我尝试了 ipcRender 和 ipcMain,但这种方法只在 Electron 内部有效,我想从 Electron 发送的数据不会传递到 UI。

有没有人有类似的经验并愿意分享您的解决方案? 请和非常感谢。

经过几天的研究和测试我的代码,我终于让它工作了!

感谢这篇文章帮助我理解了我遇到的 ipcRender 和 ipcMain 问题。 对于想要做类似事情的人,这就是我的做法。

在位于云端的 UI 代码中,添加以下代码:

const ipcRenderer = window.require('electron').ipcRenderer;
ipcRenderer.send('notes', "the msg from the cloud UI");

在 Electron 的 main.js 中,添加以下代码:

import { ipcMain } from 'electron'

//inside the createWindow function
ipcMain.on('notes', function(event, data) {
   console.log('notes: ', data)
   mainWindow.webContents.send('notes2', data) //send message back to webview
})

在 Electron 的 webview 标签中,添加以下代码:

<webview src={the_UI_url}
    nodeIntegration
  preload="file:{the_exact_path_of_preload.js}/preload.js"></webview>

必须包含nodeIntegration ,否则,您将收到错误window.require is not a function in the UI code

在 preload.js 中,添加以下代码:

const { ipcRenderer } = require('electron')

ipcRenderer.on('notes2', function(event, data) {
    console.log('notes2: ', data);
});

添加所有这些代码后,我成功地在 Electron 控制台中看到了“来自云 UI 的消息”。

您可以使用executeJavaScript函数。

<webview>.executeJavaScript(`receiveMessage("My message!")`);

在您的<webview> ,会有一个接收消息的函数:

function receiveMessage(message){
    //Do something with `message`
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM