【问题标题】:Communicate with <webview> in Electron在 Electron 中与 <webview> 通信
【发布时间】:2020-05-04 05:02:58
【问题描述】:

我的 Electron 应用中有一个 &lt;webview&gt;。我想进行安全的“对外”交流,就像我通过iframepostMessage 一样。比如:

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

我与此子webview 通信的唯一选择是打开nodeIntegration 以便我可以使用sendToHost?只为这一功能打开所有nodeIntegration 似乎有点过头了。

【问题讨论】:

    标签: electron


    【解决方案1】:

    您可以在 webview preload 脚本中访问 Electron 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:

    <script>
      const webview = document.getElementById('mywebview')
      webview.addEventListener('ipc-message', event => {
        // prints "ping"
        console.log(event.channel)
      })
    </script>
    

    【讨论】:

    • 这正是我正在寻找的答案。这适用于从 web 视图向窗口发送消息。如何将消息从窗口发送到 web 视图?
    • @HolgerEdwardWardlowSindbæk 你试过webview.send() 吗?
    • @psulek 我最终弄明白了。我想我最终使用了 webview.send() 呀。谢谢。
    • 嗨,我正在尝试同样的事情,但似乎没有工作discuss.atom.io/t/…
    • Windows 有类似的东西吗?还是需要子窗口与主进程通信才能与其他窗口通信?
    【解决方案2】:

    最简单的方法
    沟通是

    注意: (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 或 window 获取数据(我直接发送表单组件)

    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 到窗口

    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])
    
    }
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-09
      • 1970-01-01
      • 2021-06-06
      • 2017-12-26
      • 2019-10-27
      • 1970-01-01
      • 2019-05-10
      • 2018-11-08
      相关资源
      最近更新 更多