gpt4 book ai didi

electron - 如何从主进程调用渲染器 View 中的函数

转载 作者:行者123 更新时间:2023-12-03 08:13:57 25 4
gpt4 key购买 nike

我正在尝试将一些数据从主进程发送到渲染器(浏览器 View ),但似乎遇到了障碍。

当我调用window.webContents.send时,该事件只能在预加载中被捕获。我想使用这个函数修改渲染器上的数据(修改屏幕的内容)。

预加载似乎是一条相当单向的道路,我可以从 html View 中调用方法,但是如何从预加载中调用 html View ?

或者如何将信息从主视图发送到渲染器 View 并在那里修改 html?

有什么建议吗?

最佳答案

When I call window.webContents.send, the event can be trapped only in the preload. I want to modify the data on the renderer (Modify the contents of the screen) using this function.

您可以通过预加载脚本中的上下文桥公开函数。这将允许您的渲染器设置一个接收来自主进程的消息的监听器。

这是一个计数器的玩具示例,它将增加 HTML 中的计数器:

// main process
mainWindow.webContents.send('update-counter', 1)
// preload
const { contextBridge, ipcRenderer } = require('electron')

contextBridge.exposeInMainWorld('electronAPI', {
handleCounter: (callback) => ipcRenderer.on('update-counter', callback)
})
// renderer process
const counter = document.getElementById('counter')

window.electronAPI.handleCounter((event, value) => {
const oldValue = Number(counter.innerText)
const newValue = oldValue + value
counter.innerText = newValue
})
<!--html-->
<body>
Current value: <strong id="counter">0</strong>
<script src="./renderer.js"></script>
</body>

关于electron - 如何从主进程调用渲染器 View 中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70034378/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com