gpt4 book ai didi

javascript - 如何从 Electron 中的渲染器进程调用 preload.js 中定义的函数

转载 作者:行者123 更新时间:2023-12-04 03:42:08 31 4
gpt4 key购买 nike

this回答 建议可以在 preload.js 文件中定义一个 javascript 函数并将其附加到 window,然后从渲染器进程调用(在包含的 renderer .js 或直接作为 html 文件中的脚本)使用 window.functionName,即在 preload.js 中:

window.myFunction = function(){
//do something here that requires
//ipcRenderer
}

index.html 中:

<script>
var myButton = document.getElementById("myButtonId")
myButton.addEventListener('click', (e) => {
window.myFunction();
});
</script>

但是,当我这样做并单击按钮时,我收到错误消息未捕获类型错误:window.myFunction 不是函数。有人可以向我解释为什么会抛出此错误以及如何定义该函数吗?

最佳答案

使用Context IsolationcontextBridge .

Preload.js

 const { contextBridge } = require('electron')
contextBridge.exposeInMainWorld('YourAPI',
{
yourFunction: () => {'Your Codes.'}
});

你的HTML.html

<html>
<head></head>
<body>
<script>
window.YourAPI.yourFunction();
</script>
</body>
</html>

关于javascript - 如何从 Electron 中的渲染器进程调用 preload.js 中定义的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65832884/

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