electron原生和的通讯交互

目录html

 

一、原因vue

2. 标签介绍node

三、代码实现:git

四、注意事项web


一、原因

开发electron项目的时候,由于每次更改新功能都要从新打包,还要作热更新的操做,npm

借鉴原生App和h5,(H5要调起原生的拍照功能,发一个信号给原生,原生接到信号唤醒摄像头,成功或者失败发个回调给H5)发现<webview>标签能够实现,api

2. <webview>标签介绍

使用 webview 标签来把 'guest' 内容(例如 web pages )嵌入到你的 Electron app 中. guest内容包含在 webview 容器中.一个嵌入你应用的page控制着guest内容如何布局摆放和表达含义.安全

与 iframe 不一样, webview 和你的应用运行的是不一样的进程. 它不拥有渲染进程的权限,而且应用和嵌入内容之间的交互所有都是异步的.由于这能保证应用的安全性不受嵌入内容的影响.app

<webview> 标签的文档:https://wizardforcel.gitbooks.io/electron-doc/content/api/web-view-tag.htmldom

三、代码实现

原生代码以下:(本人是使用electron-vue搭建的项目)

一、electron的代码以下:

<template>
  <div id="wrapper">
    <webview id="foo" src="http://192.168.20.15:3000/" autosize min-width='1200' style="height: 700px" nodeintegration></webview>
  </div>
</template>
<script>
  export default {
    name: 'landing-page',
    data () {
      return {}
    },
    mounted () {
      this.onload();
    },
    methods: {
      onload() {
        var webview = document.getElementById("foo");
        var loadstart = () => {
          console.log("loadstart");
        }
        var loadstop = () => {
          console.log("loadstop");
        }
        webview.addEventListener("did-start-loading", loadstart);
        webview.addEventListener("did-stop-loading", loadstop);
        webview.addEventListener('dom-ready', () => {
          webview.openDevTools()//webview加载完成,能够处理一些事件了
        })
        // 在此监听事件中接收webview嵌套页面所响应的事件
        webview.addEventListener('ipc-message', function(event) {
          console.log('在此监听事件中接收webview嵌套页面所响应的事件', event.channel);
          if (event.channel === 'print') {
            // 原生处理打印成功后,告诉嵌入页面
            webview.send('ping', '打印成功') // 向webview嵌套的页面发送信息
          }
        });
      }
    }
  }
</script>

二、嵌入页的步骤

(1)安装electron  cnpm install electron -S

  (2)代码以下

<template>
  <div>
     <div @click.stop.prevent="print">点击打印按钮</div>
  </div>
</template>
<script>
export default {
  name: 'login',
  methods: {
    print() {
      // 没有在electron里面嵌入,不可用
      if (window.require) {
        const {ipcRenderer} = window.require('electron');
        ipcRenderer.sendToHost('print') // 向原生发送信息
        ipcRenderer.on('ping', (event, message) => { // 接收electron原生返回的信息
          console.log('接收electron原生返回的信息', event, message);
        })
      }
    }
  }
};
</script>

四、注意事项

问题一:在安装electron,引进的时候报错fs.existsSync is not a function、

缘由:直接require会致使提示找不到fs模块,须要使用window.require,可是在Chrome环境中提示window.require not function因此须要作一次判断

解决方案:

 if (window.require) {     var ipc = window.require('electron').ipcRenderer   }