08.《Electron 跨平台开发实战》- chapter08-深入集成(shell模块)动态启动菜单项

Posted easy5

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了08.《Electron 跨平台开发实战》- chapter08-深入集成(shell模块)动态启动菜单项相关的知识,希望对你有一定的参考价值。

在渲染进程(UI界面)中使用shell模块

//在文件管理器中打开
const { ..., shell } = require(‘electron‘);

const showFile = () => {
    if (!filePath) { return alert(‘This file has not been saved to the file system.‘); }
    shell.showItemInFolder(filePath);
};

//使用默认程序打开
const openInDefaultApplication = () => {
    if (!filePath) { return alert(‘This file has not been saved to the file system.‘); }
    //electron-9.x 已经不存在了
    shell.openItem(fullPath)
};

在应用菜单中使用 shell 模块

  • applicationMenu.js
 { type: ‘separator‘ },
        {
          label: ‘Show File‘,
          enabled: hasFilePath,
          click(item, focusedWindow) {
            if (!focusedWindow) {
              return dialog.showErrorBox(
                ‘Cannot Show File‘s Location‘,
                ‘There is currently no active document show.‘
              );
            }
            focusedWindow.webContents.send(‘show-file‘);
          },
        },
        {
          label: ‘Open in Default Application‘,
          enabled: hasFilePath,
          click(item, focusedWindow) {
            if (!focusedWindow) {
              return dialog.showErrorBox(
                ‘Cannot Open File in Default Application‘,
                ‘There is currently no active document to open.‘
              );
            }
            focusedWindow.webContents.send(‘open-in-default‘);
          },
        },
  • renderer.js
ipcRenderer.on(‘show-file‘, showFile);
ipcRenderer.on(‘open-in-default‘, openInDefaultApplication);

在上下文菜单中使用 shell 模块

  • renderer.js

//上下文菜单
const markdownContextMenu = Menu.buildFromTemplate([
...
    {
        label: ‘Show File in Folder‘,
        click: showFile,
        enabled: !!filePath
      },
      {
        label: ‘Open in Default‘,
        click: openInDefaultApplication,
        enabled: !!filePath
      },
    { type: ‘separator‘ },
   ...
]);

markdownView.addEventListener(‘contextmenu‘, (event) => {
    event.preventDefault();
    markdownContextMenu.popup();
});

禁用菜单项

以上是关于08.《Electron 跨平台开发实战》- chapter08-深入集成(shell模块)动态启动菜单项的主要内容,如果未能解决你的问题,请参考以下文章

Electron实战:创建ELectron开发的window应用安装包

Electron开发实战 美团高级前端工程师带你开发完整桌面应用

初识Electron开发桌面应用

2021-05-07

前端实战:electron+vue3+ts开发桌面端便签应用

Electron 初体验