electron入门之试调工具remote(三)

electron入门到入土,从渲染线程中创建新窗口。2022-03-21入门版本17.1.2
electron重要概念,只有一个主线程,其他都是渲染进程或者叫子线程,他们不能直接相互操作,可以通过ipcMainipcRenderer进行相互事件操作,低版本前用remote很好使,百度上的基本是老版本的教程。因为electron14+后remote被重写:https://www.electronjs.org/zh/docs/latest/breaking-changes#计划重写的-api-140
所以用remote需要安装,但是remote还是很好的数据交互组件。

开发前端经常需要使用开发者试调工具,我们可以在主线程中通过mainWindow.webContents.openDevTools()打开:

    // 加载 index.html
    mainWindow.loadFile('views/index.html')
    mainWindow.webContents.openDevTools() // 打开开发工具

可以通过事件通信实现:

主线程中:
const {app, BrowserWindow, ipcMain} = require('electron')
 // 打开开发工具
 ipcMain.on("openDevTools", (event, data) => {
     mainWindow.webContents.openDevTools()
 })

渲染/子线程中
<script>
    const {ipcRenderer} = require('electron');
    function handleKeyPress(event) {
        console.log(`You pressed ${event.key}`)
        if (event.key === 'F12') {
            // 发送 hello-console 事件
            ipcRenderer.send('openDevTools','')
        }else if(event.key==='F5'){
            window.location.reload()
        }
    }
    window.addEventListener('keyup', handleKeyPress, true)
</script>

按F12打开
在这里插入图片描述
还能用remote直接打开获取

// 安装
npm install --save @electron/remote

初始化:主线程中
// in the main process:
require('@electron/remote/main').initialize()
// 渲染线程开启remote electron 14+
require("@electron/remote/main").enable(webContents)
// 例如我的
require("@electron/remote/main").enable(mainWindow.webContents)

渲染线程中使用:
// 获取当前窗口对象
    const currentWindow = require('@electron/remote').getCurrentWindow();
    function handleKeyPress(event) {
        console.log(`You pressed ${event.key}`)
        if (event.key === 'F12') {
            // 发送 hello-console 事件
            ipcRenderer.send('openDevTools','')
        }else if(event.key==='F5'){
            window.location.reload()
        }else if (event.key==='F1'){
            currentWindow.webContents.openDevTools()
        }
    }
    window.addEventListener('keyup', handleKeyPress, true)

按F1 打开
在这里插入图片描述
关于electron的开发工具,按个人习惯,例如我是后端开发,习惯用idea,那么我就用idea开发electron,开发vue cli也是用idea,说实话,我用不惯vs code,个人推荐用idea开发。

posted @ 2022-09-16 00:08  凌康  阅读(300)  评论(0编辑  收藏  举报