electron加载远程和本地右键菜单冲突问题处理
2023-04-14 11:05 Lecone.JY.HU 阅读(270) 评论(0) 收藏 举报electron 加载远程页面,远程页面有自己的右键,但是electron也有自己的菜单,为了防止两个右键菜单同时显示,使用window.myrightmenu 进行限制,window.myrightmenu非空则显示远程的,window.myrightmenu为空则显示electron的默认菜单。
下面是远程界面代码:
// 右键 rightClick (row, column, event) { window.myrightmenu=function(){} ... }
// 列表右击事件
async TableRightFn (EvnName) {
window.myrightmenu=null;
...
}
// 鼠标移出 右键按钮
modifyReportMouseLeave (refName) {
window.myrightmenu=null
...
}
electron 中监测 window.myrightmenu ,window.myrightmenu==null || window.myrightmenu==undefined 则会插入默认的右键菜单,否则不会显示。
以下为electron中的代码:
window.document.addEventListener('contextmenu', function (e) {
// 右键事件触发
console.log('window.myrightmenu->', window.myrightmenu);
if (window.myrightmenu == null || window.myrightmenu == undefined) {
e.preventDefault();
var m = e.path[0].type === "text" || e.path[0].tagName.toLowerCase() === "textarea" || e.path[0].isContentEditable;
data = {
msg: getSelection(),
input: m
};
ipcRenderer.send('contextMenu', data);
}
})
window.document.addEventListener('mousedown', function (e) {
console.log('mousedown', e.button)
if (e.button == 0) {
window.myrightmenu = null
} else if (e.button == 1) {
window.myrightmenu = null
//alert('你按下了鼠标滚轮!');
} else {
//alert('您按下了鼠标右键!')
}
//e.preventDefault();
})
const { remote, clipboard,Menu, MenuItem } = require('electron'); //const { Menu, MenuItem } = remote function getContextMenu () { //new一个菜单 // // 监听contextmenu,实现自定义右键菜单 // window.addEventListener('contextmenu', function (e) { // 监听contextmenu,实现自定义右键菜单 window.addEventListener('contextmenu', function (e) { e.preventDefault() let menu = new Menu() //添加菜单功能, label: 菜单名称, accelerator:快捷键,click:点击方法 menu.append(new MenuItem({ label: '复制', accelerator: 'CommandOrControl+C', click: copyText })) //添加菜单分割线 menu.append(new MenuItem({ type: 'separator' })) //添加菜单功能 menu.append(new MenuItem({ label: '粘贴', accelerator: 'CommandOrControl+V', click: printText })) menu.popup(remote.getCurrentWindow()) }, false) // 写入剪贴板方法 function copyText () { const str = getSelection() // 获取选中内容 clipboard.writeText(str) // 写入剪贴板 } // 获取剪贴版内容写入当前焦点元素中 function printText(){ if (document.activeElement) { const str = clipboard.readText() // 获取剪贴板内容 var ev = new Event('input', { bubbles: true}); ev.simulated = true; document.activeElement.value = str; // 写入焦点元素 document.activeElement.dispatchEvent(ev); // clipboard.clear() // 清空剪贴板,一般都不做清空,爱粘贴就粘贴,干嘛要粘贴完就清空呢 } } // 获取选中内容 function getSelection () { var text = '' if (window.getSelection) { // 除IE9以下 之外的浏览器 text = window.getSelection().toString() } else if (document.selection && document.selection.type !== 'Control') { //IE9以下,可不考虑 text = document.selection.createRange().text } if (text) { return text } } } module.exports={ getContextMenu }
浙公网安备 33010602011771号