技术思绪摘录旅行笔记
Electron一个使用HTML、CSS和JavaScript开发桌面应用程序的框架。Electron可以生成在Windows、macOS和Linux上运行的应用程序,借助Electron可以把我们的web端应用直接移植到桌面端而无需再次开发,这样我们可以使用同一套代码在不同平台上运行应用,极大的缩短了开发时间。

Electron 主进程和渲染进程的通信主要用到两个模块:ipcMain 和 ipcRenderer

ipcMain:当在主进程中使用时,它处理从渲染器进程(网页)发送出来的异步和同步信息,当然也有可能从主进程向渲染进程发送消息。

ipcRenderer: 使用它提供的一些方法从渲染进程 (web 页面) 发送同步或异步的消息到主进程。 也可以接收主进程回复的消息。

const { app, BrowserWindow } = require("electron");
const path = require("path");

const createWindow = () => {    
    const mainWindow = new BrowserWindow({
        width: 800,
        height: 600,
        webPreferences:{
            nodeIntegration:true, //开启渲染进程中使用nodejs 
            contextIsolation:false, //开启渲染进程中使用nodejs              
        }
    });

    //在渲染进程中开启调试模式
    mainWindow.webContents.openDevTools()

    mainWindow.loadFile(path.join(__dirname, "index.html"));

    //自定义右键菜单
    require('./ipcMain/contextMenu');
}

//监听应用的启动事件
app.on("ready", createWindow)

//监听窗口关闭的事件,关闭的时候退出应用,macOs 需要排除 
app.on('window-all-closed', () => {

    if (process.platform !== 'darwin') {
        app.quit();
    }
});

//Macos 中点击 dock 中的应用图标的时候重新创建窗口 
app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
        createWindow();
    }
});

index.html引入渲染进程index.js,利用ipcRenderer给主进程发送了一个消息

const { ipcRenderer } = require('electron');

window.onload=()=>{
     //右键菜单
     window.addEventListener("contextmenu", (e) => {
         e.preventDefault()
         //弹出右键菜单  menuBuilder.popup({window:remote.getCurrentWindow()});
         ipcRenderer.send("showContextmenu");
   }, false)
}

contextMenu.js,主进程中监听消息 弹出菜单

const { Menu,ipcMain,BrowserWindow } = require("electron");

var contextTemplate = [
    { label: '复制', role: 'copy' },
    { label: '黏贴', role: 'paste' },
    { type: 'separator' },
    //分隔线 
    { label: '其他功能', click: () => { console.log('click') } }
];

var menuBuilder=Menu.buildFromTemplate(contextTemplate);

//监听右键菜单
ipcMain.on("showContextmenu",()=>{
    //渲染进程中获取当前窗口的方法 remote.getCurrentWindow() 
    //主进程中获取当前窗口的方法 BrowserWindow.getFocusedWindow()
    menuBuilder.popup({window:BrowserWindow.getFocusedWindow()});
})


CarsonIT 微信扫码关注公众号 策略、创意、技术

留下您的脚步

 

最近评论

查看更多>>

站点统计

总文章数:275 总分类数:18 总评论数:88 总浏览数:128.22万

精选推荐

阅读排行

友情打赏

请打开您的微信,扫一扫