与< 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(‘一切完成!’));
与该子Webview进行通讯是打开 nodeIntegration $ c $的唯一选择c>以便我可以使用
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
nodeIntegration 的情况下,也包括IPC在内的 rel = noreferrer>预加载脚本。您的预加载脚本可以将函数注入到全局名称空间中,然后可以在 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屋!