【问题标题】:Is there a way to pass data from Electron to the URL in the webview?有没有办法将数据从 Electron 传递到 web 视图中的 URL?
【发布时间】:2020-01-04 00:14:33
【问题描述】:

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

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

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

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

【问题讨论】:

标签: javascript electron


【解决方案1】:

您可以使用executeJavaScript 函数。

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

在您的&lt;webview&gt; 中,会有一个函数可以接收消息:

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

【讨论】:

  • 您的解决方案是最好的!非常感谢!
  • @NathanielEskenazi,很高兴我能帮上忙!
【解决方案2】:

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

Thanks to this post 帮助我了解我遇到的 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,否则你会在UI代码中得到window.require is not a function的错误

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

const { ipcRenderer } = require('electron')

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

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

【讨论】:

  • 我如何在上面的例子中传递数据?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-04
  • 1970-01-01
  • 1970-01-01
  • 2020-03-02
  • 1970-01-01
相关资源
最近更新 更多