与 <webview> 通信在电子 [英] Communicate with <webview> in Electron
问题描述
我的 Electron 应用中有一个 <webview>
.我想进行安全的外部"通信,就像我通过 postMessage
使用 iframe
的方式一样.比如:
I have a <webview>
in my Electron app. I'd like to have safe "foreign" communication, the way I would with an iframe
through postMessage
. So for example:
webview.executeJavaScript("window.parent.postMessage('all done!')");
是我与此子 Web 视图通信的唯一选择是打开 nodeIntegration
以便我可以使用 sendToHost
?只为这一功能打开所有 nodeIntegration
似乎有点过头了.
Is my only choice for communication with this subwebview to turn on nodeIntegration
so that I can use sendToHost
? Turning on all of nodeIntegration
just for this one feature seems like overkill.
推荐答案
您可以在 webview
preload 脚本,包括 IPC,即使 nodeIntegration
被禁用.您的预加载脚本可以将函数注入全局命名空间,然后可以在 webview
中加载的页面中访问这些函数.一个简单的例子:
You can access Electron APIs in the webview
preload script, including IPC, even when nodeIntegration
is disabled. Your preload script can inject functions into the global namespace that will then be accessible within the page loaded in the webview
. A simple example:
webview-preload.js
:
const { ipcRenderer } = require('electron')
global.pingHost = () => {
ipcRenderer.sendToHost('ping')
}
webview-index.html
:
<script>
pingHost()
</script>
window-index.html
:
<script>
const webview = document.getElementById('mywebview')
webview.addEventListener('ipc-message', event => {
// prints "ping"
console.log(event.channel)
})
</script>
这篇关于与 <webview> 通信在电子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!