在Electron中与<webview>进行通信

时间:2016-09-11 22:57:04

标签: electron

我的Electron应用中有一个<webview>。我希望通过iframepostMessage进行安全的“外国”沟通。例如:

webview.executeJavaScript("window.parent.postMessage('all done!')");

是我与此子浏览器进行通信的唯一选择是打开nodeIntegration以便我可以使用sendToHost吗?为这一个功能打开所有nodeIntegration似乎有点矫枉过正。

2 个答案:

答案 0 :(得分:23)

即使禁用 <img src="file://///06imagestore\RSVP\20141105_074252.jpg" width="960"> ,您也可以使用webview preload脚本访问电子API,包括IPC。您的预加载脚本可以将函数注入全局命名空间,然后可以在nodeIntegration中加载的页面中访问该命名空间。一个简单的例子:

webview

webview-preload.js

const { ipcRenderer } = require('electron') global.pingHost = () => { ipcRenderer.sendToHost('ping') }

webview-index.html

<script> pingHost() </script>

window-index.html

答案 1 :(得分:3)

最简单的方法
沟通是

注意: (main.js或app.js或background.js或process.js)无需传递(直接将组件传递到组件),我已成功在电子版中实现:3.1.10 用于打印html webview。

Web视图窗口

example1.html

    <webview id="paper" style="width:300px;height:800px" src="file:///static/mywebview.html" nodeintegration></webview>

example1.js

 var webview = document.getElementById("paper");
  webview.send("ping",data); 

从mycomponent或窗口中获取数据(我直接从表单组件发送数据)

mywebview.html

<!---what data you want show----!>

mywebview.js

    const {
        ipcRenderer
    } = require('electron')                                                                            
  //data from window                                                                   
    ipcRenderer.on('ping', (e, data) => { console.log(data) })

网页查看窗口

Webview到窗口(直接传递到组件)

mywebview.js

 ipcRenderer.sendToHost("readyCompanyInfo",data) 

在我的窗口中,例如,我使用vue(mycomponent.vue或mypage)

example1.html

const ipcRenderer = require("electron").ipcRenderer;
webview.addEventListener("ipc-message",(event)=>{

const {args,channel}=event;

if(channel=="readyCompanyInfo")
{
console.log(channel,args)
//here you can see data what u passed from webview to window
console.log(args[0])

}
})