使用 Electron 实现一个简单的文本编辑器

文本编辑页面

html 复制代码
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>文本编辑器</title>
</head>
<body>
    <textarea id="text-editor"></textarea>
    <script src="./renderer.js"> </script>
    <style>
        html, body{height:100%;display: flex;flex: 1;flex-direction: column;}
        textarea {display: flex; width: 100%;height: 100%; border: none;outline: none;}
    </style>
</body>
</html>

自定义菜单

自定义应用程序菜单

cpp 复制代码
const { app, ipcMain, BrowserWindow, Menu, dialog } = require('electron');
const template = [
    {
    label: '文件',
    submenu: [
      { label: '打开文件', accelerator: 'Ctrl+O', click: () =>  openFile()},
      { label: '保存文件', accelerator: 'Ctrl+S', click: () => saveFile()},
      { type: 'separator' },
      { role: 'close', label: '关闭窗口' },
      { role: 'quit', label: '退出应用' }
    ]
  },
  {
    // 编辑菜单
    label: '编辑',
    submenu: [
      { role: 'undo' },
      { role: 'redo' },
      { type: 'separator' },
      { role: 'cut' },
      { role: 'copy' },
      { role: 'paste' },
      { role: 'selectAll' }
    ]
  },
  {
    // 帮助菜单
    label: '调试',
    submenu: [
      { 
        role: 'toggleDevTools', 
        label: '开发者工具'
      }
    ]
  }
];

label 用来设置菜单的文本,accelerator 用于设置快捷键,click 用于设置点击后要执行的操作,submenu 为子菜单

type: 'separator' 表示分隔符,role 则是 electron 预设的一些菜单选项,我们可以直接使用它们,而不需要自己再去实现这些功能。读者可访问 https://www.electronjs.org/docs/latest/api/menu-item 来查看 electron 预设了哪些 role。

cpp 复制代码
const appMenu = Menu.buildFromTemplate(template);
Menu.setApplicationMenu(appMenu);

使用我们定义好的模板创建一个 menu,然后设置应用程序菜单为我们定义的菜单。

右键菜单

cpp 复制代码
const menu = Menu.buildFromTemplate([
    { role: 'copy' },
    { role: 'cut' },
    { role: 'paste' },
    { role: 'selectall' }
  ]);
  window.webContents.on('context-menu', (_event, params) => {
    if (params.isEditable) {
      menu.popup()
    }
  });

右键菜单也是类似的,根据模板创建一个 menu 实例,然后在 contex-menu 事件响应里将其弹出。

文件的加载和保存

现在我们已经完成了页面的构建,接下来我们需要实现文件的加载和保存。

javascript 复制代码
const { canceled, filePaths } = await dialog.showOpenDialog({
        properties: ['openFile'],
        filters: [
            { name: '文本文件', extensions: ['txt'] },
            { name: '所有文件', extensions: ['*'] }
        ]
    });

使用 dialog.showOpenDialog 打开文件选择对话框,获取文件路径。

javascript 复制代码
const fs = require('fs').promises;

导入 fs 模块

javascript 复制代码
    const content = await fs.readFile(filePath, 'utf-8');
    currentFilePath = filePath; // 保存当前文件路径
    window.webContents.send('file-opened', { filePath, content });

读取文件内容,并把文件内容发送到渲染进程

javascript 复制代码
const {ipcRenderer, contextBridge } = require('electron')
contextBridge.exposeInMainWorld('fileApi', {
    onFileOpened: (callback) => {
        ipcRenderer.on("file-opened", (_event, data) => {
            callback(data);
        });
    }
});

预加载脚本添加 "file-opened" 事件处理,并暴露 fileApi 对象

javascript 复制代码
window.fileApi.onFileOpened((data) => {
    const { filepath, content } = data;
    const textArea = document.getElementById('text-editor');
    textArea.value = content;
});
document.addEventListener('DOMContentLoaded', () => {
    const textArea = document.getElementById('text-editor');
    textArea.focus();
});

渲染进程脚本注册回调函数,将文件内容设置到 textArea 中,这里还添加了 DOMContentLoaded 事件监听,这是因为如果没有这个处理,会导致文件内容设置后,编辑器无法唤起中文输入法。

完整代码可以在 https://github.com/ZhongxianWang/electron-app 仓库里找到。

相关推荐
Coder_Boy_2 分钟前
基于SpringAI的在线考试系统-考试系统DDD(领域驱动设计)实现步骤详解(2)
java·前端·数据库·人工智能·spring boot
GIS之路8 分钟前
ArcGIS Pro 实现影像波段合成
前端·python·信息可视化
m0_7482546614 分钟前
CSS id 和 classid 和 class 选择器
前端·css
光算科技21 分钟前
单页应用SEO可行性丨Angular项目的3个索引优化方案
前端·javascript·angular.js
ggaofeng26 分钟前
实践NPM打包和使用
前端·npm·node.js
一只小bit31 分钟前
Qt MainWindow:主窗口组件的介绍与正确使用
前端·c++·qt
Macbethad1 小时前
半导体EFEM设备TwinCAT程序设计方案
java·前端·网络
ggaofeng1 小时前
理解npm的原理
前端·npm·node.js
摘星编程1 小时前
React Native for OpenHarmony 实战:SnapCarousel 轮播组件详解
javascript·react native·react.js
电商API_180079052471 小时前
1688商品详情采集API全解析:技术原理、实操指南与业务落地
大数据·前端·人工智能·网络爬虫