Electron禁止開啟開發者工具

槑孒發表於2024-06-27

為了禁止在Electron應用中開啟開發者工具,可以透過設定BrowserWindow的選項以及監聽和處理相關事件來實現。

示例

步驟

  1. 初始化專案:如沒有初始化專案,可執行以下命令:

    mkdir my-electron-app
    cd my-electron-app
    pnpm init
    
  2. 安裝Electron

    pnpm add electron
    
  3. 建立專案結構

    建立一個 main.js 檔案,並新增以下內容:

    const { app, BrowserWindow } = require('electron')
    
    function createWindow () {
      const win = new BrowserWindow({
        width: 800,
        height: 600,
        webPreferences: {
          nodeIntegration: true,
          devTools: false // 禁用開發者工具
        }
      })
    
      win.loadFile('./pages/index.html')
    
      // 禁用選單欄中的開發者工具選項
      win.removeMenu()
    
      // 禁用鍵盤快捷鍵
      win.webContents.on('before-input-event', (event, input) => {
        if (input.key === 'F12' || (input.control && input.shift && input.key === 'I')) {
          event.preventDefault()
        }
      })
    }
    
    app.whenReady().then(createWindow)
    
    app.on('window-all-closed', () => {
      if (process.platform !== 'darwin') {
        app.quit()
      }
    })
    
    app.on('activate', () => {
      if (BrowserWindow.getAllWindows().length === 0) {
        createWindow()
      }
    })
    

    建立一個 index.html 檔案,並新增以下內容:

    <!DOCTYPE html>
    <html>
      <head>
        <title>Hello Electron</title>
      </head>
      <body>
        <h1>Hello Electron</h1>
        <p>If you see this, Electron is up and running!</p>
      </body>
    </html>
    
  4. package.json 中新增啟動指令碼

    {
      "name": "my-electron-app",
      "version": "1.0.0",
      "main": "main.js",
      "scripts": {
        "start": "electron ."
      },
      "dependencies": {
        "electron": "^31.1.0"
      }
    }
    
  5. 啟動應用

    pnpm start
    

這樣,Electron應用啟動時,開發者工具將會被禁用。

相關文章