为了禁止在Electron应用中打开开发者工具,可以通过设置BrowserWindow
的选项以及监听和处理相关事件来实现。
https://www.electronjs.org/zh/docs/latest/
示例
步骤
- 初始化项目:如没有初始化项目,可执行以下命令:
mkdir my-electron-app
cd my-electron-app
pnpm init
- 安装Electron:
pnpm add electron
- 创建项目结构:
创建一个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>
- 在
package.json
中添加启动脚本:
{
"name": "my-electron-app",
"version": "1.0.0",
"main": "main.js",
"scripts": {
"start": "electron ."
},
"dependencies": {
"electron": "^31.1.0"
}
}
- 启动应用:
pnpm start
这样,Electron应用启动时,开发者工具将会被禁用。