Vite - Electron - IPC

4 篇文章 0 订阅
3 篇文章 0 订阅

1.代码记录

$ /electron/index.ts

  1. above vite 3.2.41
  2. electron 27.0.3
  3. electron-builder 24.6.4
import { app, BrowserWindow, Menu, globalShortcut, clipbord } from 'electron'

let win: BrowserWindow | null
let currentWin: BrowserWindow | null

function loadSelection () {
    return currentWin?.webContents.executeJavaScript(`
	(function () {
		const data = window.getSelection()
		return Promise.resolve(data)
	})()`, true)
}

const ctxMenu = Menu.buildFromTemplate([
    {
        label: '返回', id: 'back', accelerator: 'Alt + Left',
        click () {
            currentWin?.webContents.goBack()
        }
    },
    {
		label: '复制', id: 'copy', role: 'copy', accelerator: 'Ctrl + C',
    },
    {
		label: '粘贴', id: 'paste', role: 'paste', accelerator: 'Ctrl + V',
    },
    {	
        label: '查找', id: 'find', accelerator: 'Ctrl + F',
        click () {
            loadSelection()?.then((r) => {
                // currentWin?.webContents.findInPage(r, { findNext: true })
            })
        }
    },
])

function setMenuVis (menu: Menu, shows: string[]) {
    const keys = ['reload'].concat(shows)
    for (const item of menu.items) {
        item.visible = keys.includes(item.id)
    }
    return menu
}

function createWindow () {
    win = new BrowserWindow({})
    
    // above vite 3.2.41
    if (process.env.VITE_DEV_SERVER_URL) {
        win.loadURL(process.env.VITE_DEV_SERVER_URL)
    }
}

app.whenReady().then(() => {
    globalShortcut.register('CmdOrCtrl + F', () => {
        loadSelection()?.then((r) => { 
            // currentWin?.webContents.findInPage(r, { findNext: true })
        })
    })
    
    createWindow()
})

const inputs = ['plainText', 'password']
app.on('browser-window-created', (_, win) => {
    currentWin = win
    // hide the menu
    win.setMenu(null)
    
    win.webContents.on('context-menu', (_, params) => {
        const shows: string[] = []
        if (win.webContents.canGoback()) {
            shows.push('back')
        }
        if (params.selectionText) {
            shows.push('copy')
        }
        const ready = inputs.includes(params.inputFieldType)
        if (ready && clipbord.readText()) {
            shows.push('paste')
        }
        if (ctxMenu.items.length) {
            setMenuVis(ctxMenu, shows).popup()
        }
    })
    
    win.webContents.on('found-in-page', (_, result) => {
        // console.log(result)
    })
})

app.on('browser-window-focus', (_, win) => {
    currentWin = win
})

2.问题记录

  1. 通过a标签,打开新窗口时,添加右键菜单

    app.on('browser-window-created', (_, win) => {
        // Obtain the created window object and listen for the context-menu event
        currentWin = win
        
        win.webContents.on('context-menu', (_, params) => {
            // TODO
        })
    })
    
  2. 通过electron API 无法获取页面上选中文本

    // Inject JavaScript logic through the corresponding API
    function loadSelection () {
        return currentWin?.webContents.executeJavaScript(`
    	(function () {
    		const data = window.getSelection()
    		return Promise.resolve(data)
    	})()`, true)
    }
    
  3. 通过 findInPage 实现页面文本信息搜索

    $ /electron/preload.ts

    import path from 'path'
    import { app, BrowserWindow } from 'electron'
    
    // Customize the window
    const win = new BrowserWindow({
        webPreferences: {
            // You can configure the preload attribute to inject the logic for creating the module
            preload: path.join(__dirname, 'preload')
        }
    })
    
    // Non-custom windows
    // The logic for creating the module is injected through the executeJavaScript function
    win?.webContents.executeJavaScript(``)
    
    // Inject CSS styles uniformly
    win.webContents.insertCSS(``)
    
    // Repeatedly call the findInPage function to search for text from the front to the end
    win?.webContents.findInPage(r, { findNext: true })
    

3.渲染进程 / 主进程 通信(IPC)

1. ipcRenderer

$ 默认情况下,vite 不支持 ipcRenderer,得安装插件 vite-plugin-electron-renderer 让其支持

# vite-plugin-electron-renderer 0.14.5
yarn add -D vite-plugin-electron-renderer

$ /vite.config.ts

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import electron from 'vite-plugin-electron'
import electronRender from 'vite-plugin-electron-renderer'
 
export default defineConfig({
  plugins: [
      vue(),
      electron([
          {
              entry: "electron/index.ts"
          },
          {
             entry: "electron/preload.ts" 
          }
      ]),
      electronRender()
  ],
})

2. IPC代码记录

$ /electron/index.ts

import { app, BrowserWindow, Menu, globalShortcut, ipcMain } from 'electron'

function createWindow () {
    win = new BrowserWindow({})
    
    ipcMain.on('transfer', (event, data) => {
        console.log('log data', data)
        event.sender.send('sing', 'This is a example')
    })
    
    // above vite 3.2.41
    if (process.env.VITE_DEV_SERVER_URL) {
        win.loadURL(process.env.VITE_DEV_SERVER_URL)
    }
}

$ /src/components/HelloWord.vue

<script setup lang="ts">
    import { onMounted } from 'vue'
	import { ipcRenderer } from 'electron'

    onMounted(() => {
		setTimeout(() => {
            ipcRenderer.send('transfer', 'ipcMain')
        }, 6000)
		ipcRenderer.on('sing', (_, data) => {
            console.log('to sing', data)
        })
    })
</script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值