electron - 如何在Electron中使用contextBridge创建contextMenu(右键单击菜单)

标签 electron

问题
您好,我是 Electron 初学者。
我知道使用 contextBridge 是在Electron中制作安全应用的好方法。
我想在contextMenu中实现一个contextBridge(右键单击菜单),以指定对Renderer进程中的Main进程执行哪种类型的进程,但是我不能这样做。
你能给我一些建议吗?

我的密码
main.js(主进程)(初始化的一部分)

function createWindow() {
  mainWindow = new BrowserWindow({
    width: 960,
    height: 540,
    webPreferences: {
      nodeIntegration: false,
      contextIsolation: true,
      enableRemoteModule: false,
      preload: __dirname + "/preload.js"
    }
  });
  mainWindow.loadFile(__dirname + "/index.html");
}
preload.js
const contextBridge = require("electron");
const remote = require("electron").remote;
const Menu =remote.Menu;
const MenuItem=remote.MenuItem;

contextBridge.exposeInMainWorld(
  "api", {
    menu:()=>{
      const menu = new Menu();

      // label definition
      menu.append(new MenuItem({
        label: 'MenuItem1',
        click() {
          console.log('item 1 clicked');
        }
      }));

      // right clicked
      window.addEventListener('contextmenu', (e) => {
        e.preventDefault();
        menu.popup({
          window: remote.getCurrentWindow()
        });
      }, false);
    }
  }
);
index.html(渲染过程)
<!DOCTYPE html>

<html>

<head>
  <script>
    window.api.menu();
  </script>
</head>

<body>
</body>

</html>

我尝试了什么
最初,这是一个失败。

webreferences中的main.js仅更改为nodeIntegration:true(不使用contextBridge),并将menupreload.js放入<script>中的index.html,我可以实现contextMenu
但是我知道这种方法不能制作安全的应用程序,因为不使用contextBridge
main.js
function createWindow() {
  mainWindow = new BrowserWindow({
    width: 960,
    height: 540,
    webPreferences: {
      nodeIntegration: true // changing false to true, deleting the others
    }
  });
  mainWindow.loadFile(__dirname + "/index.html");
}
preload.js
没有更改(因为未加载)

index.html
<!DOCTYPE html>

<html>

<head>
  <script>
    // add the following
    const remote = require("electron").remote;
    const Menu =remote.Menu;
    const MenuItem=remote.MenuItem;

    const menu = new Menu();

    // label definition
    menu.append(new MenuItem({
      label: 'MenuItem1',
      click() {
        console.log('item 1 clicked');
      }
    }));

    // right cliced
    window.addEventListener('contextmenu', (e) => {
      e.preventDefault();
      menu.popup({
        window: remote.getCurrentWindow()
      });
    }, false);
  </script>
</head>

<body>
</body>

</html>

谢谢您的阅读。

最佳答案

我相信您的上下文菜单将不起作用,因为您正在尝试在预加载器中对其进行预加载之后对其进行构建。您需要在main.js文件中构建菜单。
这是我使用的方法。
像这样设置您的preloader.js:

// whitelist channels
let validChannels = ["load-context-menu", "pop-context-menu"];

contextBridge.exposeInMainWorld(
    "electron",
    {
        on: (channel, callback) => {
            //console.log('Channel: ' + channel);
            if (validChannels.includes(channel)) {
                ipcRenderer.on(channel, callback);
            }
        },
        sendSync: (channel, data) => {
            //console.log('Channel: ' + channel);
            if (validChannels.includes(channel)) {
                return ipcRenderer.sendSync(channel, data);
            }
        }
    }
);
然后这样称呼它:
window.electron.sendSync('load-context-menu', null);
window.electron.sendSync('pop-context-menu', null);
最后,将其添加到您的main.js文件中:
const editorContextMenuBuilder = require('./scripts/editorContextMenuBuilder');
let contextMenu;

ipcMain.on('load-context-menu', (event, arg) => {
  try {
    contextMenu = editorContextMenuBuilder();
    event.returnValue = true;
  } catch (err) {
    event.returnValue = 'LOAD CONTEXT ERROR';
  }
});
ipcMain.on('pop-context-menu', (event, arg) => {
  try{
    contextMenu.popup();
    event.returnValue = true;
  } catch (err) {
    event.returnValue = 'POP CONTEXT ERROR';
  }
});
如果需要将数据发送到菜单构建器,请在发送对象之前对其进行字符串化,然后使用JSON将其解析回main.js中。

关于electron - 如何在Electron中使用contextBridge创建contextMenu(右键单击菜单),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61706487/

相关文章:

electron - 无法在 Electron 应用程序中使用node-hid库

electron - Electron Builder Appx : The package manifest is not valid

node.js - Spectron:如何测试Electron `shell.openExternal('一些url')`

vue.js - 如何根据特定的 Vuex 状态从 Vue.js 组件内部激活/停用 Electron.js 子菜单?

node.js - 运行 “First Electron App”不会显示版本吗?

javascript - 可扩展 Electron 应用程序的架构?

electron - 引导 NW.js/Electron 应用程序

javascript - 运行带有Ajax问题的Python

node.js - 如何将 Docker 用于 Windows 内置的 ElectronJS 应用程序?

node.js - 在 Electron react 应用程序中导入 whatsapp-web.js nodejs 模块的问题