开发的Electron项目想要支持右键剪切,复制,粘贴功能,给出详细可用代码
主线程 main/index.js
import { Menu, ipcMain } from 'electron'
ipcMain.on('show-context-menu', event => {
const template = [
{
label: '剪切',
role: 'cut'
},
{
label: '复制',
role: 'copy'
},
{
label: '粘贴',
role: 'paste'
},
]
const menu = Menu.buildFromTemplate(template)
menu.popup({ window: BrowserWindow.fromWebContents(event.sender)
})
渲染线程,可以直接在App.vue 中添加一下代码
mounted() {
let _that = this
window.addEventListener('contextmenu', e => {
e.preventDefault()
if (_that.isEleEditable(e.target)) {
window.electron.ipcRenderer.send('show-context-menu')
}
})
window.electron.ipcRenderer.on('context-menu-command', (e, command) => {
// ...
})
},
methods: {
isEleEditable(e) {
if (!e) {
return false
}
//为input标签或者contenteditable属性为true
if (e.tagName == 'INPUT' || e.contentEditable == 'true') {
return true
} else {
//递归查询父节点
return isEleEditable(e.parentNode)
}
}
}
请注意,要想在渲染线程中直接使用window.electron.ipcRenderer,需要在预加载脚本中添加以下代码
preload/index.js
import { electronAPI } from '@electron-toolkit/preload'
window.electron = electronAPI
这样程序就可以在可编辑地方(输入框等)右键出现弹窗了