Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
2
Help us understand the problem. What is going on with this article?
@k-yamada-github

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

More than 1 year has passed since last update.

開発環境

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
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
k-yamada-github
Kotlin, Swift, Android, iOS, Vue.js, AWS

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
2
Help us understand the problem. What is going on with this article?