electron右鍵菜單、托盤、通知、應用菜單、文件菜單瀏覽、確認對話框


-

這次把electron更新到了當前最新版本:16.0.6

需要用yarn命令安裝,否則node install.js容易安裝失敗;

這次主要熟悉:預加載文件(preload)、菜單設置(Menu MenuItem)、導航設置、系統通知框(Notification)、消息框、確認框((dialog)、托盤(tray)、

目錄結構:

 

 

 pakage.json:

{
  "name": "electronTest",
  "version": "1.0.0",
  "description": "",
  "main": "main.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "serve": "electron ."
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "electron": "^16.0.6"
  }
}

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <!-- 安全設置 -->
  <meta http-equiv="Content-Security-Policy" content="default-src 'self' 'unsafe-inline';">
  <title>Document</title>
</head>
<body>
  <h1>Hello World!</h1>
  <span>chrome-version:</span>
  <h1 id="chrome-version"></h1>
  <span>node-version:</span>
  <h1 id="node-version"></h1>
  <span>electron-version:</span>
  <h1 id="electron-version"></h1>
  <script>
    console.log('html 頁面js執行');
  </script>
</body>
</html>

main.js

const { app, BrowserWindow, Notification, Menu, MenuItem, Tray, nativeImage, dialog, screen } = require('electron')
const path = require('path')
const menuTemplate = require('./data/menuTemplate')
// 保持一個對於 window 對象的全局引用,不然,當 JavaScript 被 GC,
// window 會被自動地關閉
var mainWindow = null;

// 當所有窗口被關閉了,退出。
app.on('window-all-closed', function() {
  // 在 OS X 上,通常用戶在明確地按下 Cmd + Q 之前
  // 應用會保持活動狀態
  if (process.platform != 'darwin') {
    app.quit();
  }
});
// 調用系統通知
const NOTIFICATION_TITLE = '通知標題'
const NOTIFICATION_BODY = '通知內容'
function showNotification () {
  new Notification({ title: NOTIFICATION_TITLE, body: NOTIFICATION_BODY }).show()
}
// 當 Electron 完成了初始化並且准備創建瀏覽器窗口的時候
// 這個方法就被調用
app.on('ready', function() {
  // 獲取屏幕寬高  可以在創建窗口時傳入,這樣就可以讓初始屏幕全屏
  const { width, height } = screen.getPrimaryDisplay().workAreaSize;
  console.log(process.platform, 'process.platform');
  // Menu.setApplicationMenu(null) //取消菜單欄
  // 創建瀏覽器窗口。
  mainWindow = new BrowserWindow({
    width: 800,
    height: 800,
    // frame: false, // windows下隱藏導航欄
    // titleBarStyle: 'hidden', // mac下隱藏導航欄
    webPreferences: {
      nodeIntegration: true, // 是否啟用Node integration. 5.0以后默認值為 false.
      contextIsolation: false, // 設置為false后,才能在渲染進程使用Electron API
      preload: path.join(__dirname, 'preload.js')
    }
  });

  // 加載應用的 index.html
  // mainWindow.loadURL('file://' + __dirname + '/index.html');
  mainWindow.loadFile('index.html');
  // 定義菜單
  const menu = new Menu();
  menu.append(new MenuItem({label: '復制', role: 'copy'}));
  menu.append(new MenuItem({label: '粘貼', role: 'paste'}));
  menu.append(new MenuItem({label: '刷新', role: 'reload'}));
  menu.append(new MenuItem({label: '全選', role: 'selectall'}));
  menu.append(new MenuItem({label: '剪切', role: 'cut'}));
  menu.append(new MenuItem({label: '刪除', role: 'delete'}));
  menu.append(new MenuItem({label: '取消', role: 'undo'}));
  menu.append(new MenuItem({label: '重置', role: 'redo'}));
  mainWindow.webContents.on('context-menu', (e, params) => {
    menu.popup({window: mainWindow, x: params.x, y: params.y});
  })
  // 設置系統托盤(系統圖標)底部菜單小三角里的圖標,而不是底部菜單的圖標
  const icon = nativeImage.createFromPath('./image/img1.png');
  const tray = new Tray(icon);
  // 給圖片圖標加上右鍵菜單
  const contextMenu = Menu.buildFromTemplate([
    { label: 'Item1', type: 'radio' },
    { label: 'Item2', type: 'radio' },
    { label: 'Item3', type: 'radio', checked: true },
    { label: 'Item4', type: 'radio' }
  ])
  tray.setContextMenu(contextMenu);
  // 給托盤加個工具提示或標題
  tray.setToolTip('This is my application')
  tray.setTitle('This is my title');
  // 確認框
  dialog.showOpenDialog(mainWindow, {
    properties: ['openFile'],
    filters:[
      {name: 'Images', extensions: ['jpg', 'png', 'gif']},
      {name: 'Movies', extensions: ['mkv', 'avi', 'mp4']},
      {name: 'Custom File Type', extensions: ['as']},
      {name: 'All Files', extensions: ['*']}
    ]
  }).then(result => {
    console.log(result.canceled)
    console.log(result.filePaths)
  }).catch(err => {
    console.log(err)
  })
  // 消息框
  dialog.showMessageBox(mainWindow, {
    type: 'warning',
    title: '消息框' + app.name,
    icon: './image/img1.png',
    defaultId: 0,
    cancelId: 1,
    message: '你確定要退出?',
    buttons: ['退出', '取消']
  }).then(r => {
    if(r.response === 0) {
      app.exit();
    } else {
      console.log(r.response);
    }
  })
  // 打開開發工具
  mainWindow.openDevTools();

  // 當 window 被關閉,這個事件會被發出
  mainWindow.on('closed', function() {
    // 取消引用 window 對象,如果你的應用支持多窗口的話,
    // 通常會把多個 window 對象存放在一個數組里面,
    // 但這次不是。
    mainWindow = null;
  });
  // 通知
  showNotification()
});

// 設置系統菜單
const list = Menu.buildFromTemplate(menuTemplate)
Menu.setApplicationMenu(list);

 

preload.js

console.log('預加載文件執行')
window.addEventListener('DOMContentLoaded', () => {
  const replaceText = (selector, text) => {
    const element = document.getElementById(selector)
    if (element) element.innerText = text
  }

  for (const type of ['chrome', 'node', 'electron']) {
    replaceText(`${type}-version`, process.versions[type])
  }
})

 

data/menuTemplate.js

const template = [
  {
    label: '首頁'
  },
  {
    label: '新聞資訊',
    submenu: [
      {
        label: '國內新聞',
        submenu: [
          {
              label: '北京新聞'
          }, {
              label: '河南新聞'
          }
        ]
      },
      {
          label: '國際新聞'
      }
    ]
  },
  {
    label: '娛樂',
    submenu: [
      {
          label: '音樂'
      }, {
          label: '電影'
      }, {
          label: '綜藝'
      }
    ]
  },
  {
    label: '科技',
    submenu: [
      {
          label: 'Al'
      },
      {
          label: '手機'
      },
      {
          label: '互聯網'
      }
    ]
  }
]

module.exports = template

 

 

-


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM