...
大前端 electronnodejs

electron 显示右键菜单 限制只对编辑框或选中文本显示右键菜单

需求:
1.只对编辑框显示右键菜单
2.只在页面文字被选中的情况下显示右键菜单
直接上代码吧!

主进程 index.js

const { app, BrowserWindow, ipcMain, Menu } = require('electron')

// 接受渲染进程消息

ipcMain.on('show-context-menu', (event, param) => {
    // 制作右键菜单
    let template = [
        { role: 'undo', label: '撤销' }, 
        { role: 'selectAll', label: '全选' }, 
        // 分割线
        { type: 'separator' }, 
        // enabled 设置选项是否可用
        { role: 'cut', label: '剪切', enabled: param.cut }, 
        { role: 'copy', label: '复制', enabled: param.copy }, 
        { role: 'paste', label: '粘贴', enabled: param.paste },
    ]
    const menu = Menu.buildFromTemplate(template)
    // 显示菜单
    menu.popup(BrowserWindow.fromWebContents(event.sender))
})

渲染进程
index.html

<script>
    const { ipcRenderer } = require('electron');
    // 监听右键
    document.addEventListener('contextmenu', function (e) {
        // 检查页面是否是有选择的文本 这里显示复制和剪切选项是否可见
        const selectText = window.getSelection().toString() ? true : false;
        if (
            // 只在有文本被选择的情况下才可以开启右键菜单
            selectText ||
            // 或者在输入框内
            e.target.tagName == "TEXTAREA" || 
            // 或者输入框是文本或者数字类型下才可以开启
            (e.target.tagName == "INPUT" && (e.target.type == "text" || e.target.type == "number"))
        ) {
            // 读取剪切板是否有文本 这里传递粘贴选项是否可见
            const paste = navigator.clipboard.readText() ? true : false;
            // 发送给主进程让它显示菜单
            ipcRenderer.send("show-context-menu", {
                paste,
                copy: selectText,
                cut: selectText,
            });
        }
    });
</script>

效果:

electron 前端使用vue 或 webpack 打包一些问题整理 electron创建圆角窗口附带阴影效果
biu biu biu
免费SSL证书、自动化续签证书,acme.sh 完整教程:安装、使用、常见错误及解决方案 分享一个微信朋友圈点赞秒赞软件,无需下载一秒几千赞 js 通过坐标计算两个坐标之间的距离 edge浏览器google浏览器显示由该组织管理由你的组织管理解决方法 共享打印机连接错误提示错误代码 0x0000000a 解决方法