为了禁止在Electron应用中打开开发者工具,可以通过设置BrowserWindow的选项以及监听和处理相关事件来实现。

https://www.electronjs.org/zh/docs/latest/

示例

步骤

  1. 初始化项目:如没有初始化项目,可执行以下命令:
mkdir my-electron-app
cd my-electron-app
pnpm init
  1. 安装Electron
pnpm add electron
  1. 创建项目结构
    创建一个 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>
  1. package.json 中添加启动脚本
{
  "name": "my-electron-app",
  "version": "1.0.0",
  "main": "main.js",
  "scripts": {
    "start": "electron ."
  },
  "dependencies": {
    "electron": "^31.1.0"
  }
}
  1. 启动应用
pnpm start

这样,Electron应用启动时,开发者工具将会被禁用。