2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

electronのwebviewとipcで通信する方法

Last updated at Posted at 2018-05-29

開発環境

electron-vue-typescript-starterをベースに実装しました。

  • electron
  • typescript
  • vue.js

実装方法

vueコンポーネントファイル

HogePage.vue
<template>
  <webview 
    src="http://localhost:3000/" 
    partition="persist:hoge"
    :preload="preload"
    autosize
    allowpopups
  />
</template>

<script lang="ts">
import Vue from "vue";

export default Vue.extend({
  name: "hoge-page",
  data () {
    return {
      preload: `file:${require('path').resolve(__dirname, '../path/to/preload.js')}`
    }
  },  
  mounted () {
    const webview: any = document.querySelector('webview')
    webview.addEventListener("ipc-message", (event: any) => {
      console.log("channel: " + event.channel)
    })

    webview.addEventListener('dom-ready', () => {
      webview.openDevTools() // webview側のデベロッパーツールを表示する。うざかったら消していい。
      webview.send("ping")
    })
  }
});
</script>

preloadファイル(javascript)

preload.js
const {ipcRenderer} = require('electron')

ipcRenderer.on('ping', (e, data) => {
  ipcRenderer.sendToHost('pong');
});

window.onload = function(event) {
  ipcRenderer.sendToHost("onload")
}

動作確認

デベロッパーツールのログに以下のように出力されれば成功

channel: onload
channel: pong

参考

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?