【发布时间】:2021-12-24 12:35:31
【问题描述】:
我想创建一个 electron.js 应用。打开的第一个窗口应该是登录窗口。但是现在我有一个问题,当我按下登录按钮时,我无法管理新的主窗口。
目前我总是收到错误:未捕获的 ReferenceError: require is not defined 在 createBrowserWindow (login.js:16) 在 HTMLFormElement。 (login.js:9)
这是我的 main.js 文件
// main.js
// Modules to control application life and create native browser window
const { app, BrowserWindow } = require('electron')
const path = require('path')
function createLoginWin() {
const loginWindow = new BrowserWindow({
width: 300,
height: 500,
minWidth: 300,
minHeight: 500,
maxWidth: 300,
maxHeight: 500,
icon: path.join(__dirname, 'assets/images/command.png'),
webPreferences: {
preload: path.join(__dirname, 'preload_login.js')
}
})
loginWindow.loadFile('./src/index.html');
loginWindow.setMenuBarVisibility(false);
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
createLoginWin()
app.on('activate', () => {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (BrowserWindow.getAllWindows().length === 0) createWindow()
})
})
// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') app.quit()
})
它基本上是来自 electron.js 文档的文件。
这是我的 html 文件:
<!--index.html-->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'">
<meta http-equiv="X-Content-Security-Policy" content="default-src 'self'; script-src 'self'">
<title>Document</title>
</head>
<body>
<div id="container">
<form id="login-form">
<input type="text" placeholder="Username or Email" id="username_in">
<input type="password" placeholder="password" id="password_in">
<button type="submit" id="submit_btn">Login</button>
</form>
</div>
<script src="./login.js"></script>
</body>
</html>
这是我的 login.js 文件:
const loginForm = document.getElementById('login-form')
loginForm.addEventListener("submit", (event) => {
event.preventDefault();
const test = document.getElementById('container')
test.style.backgroundColor = 'black';
console.log('TestHTML')
createBrowserWindow();
console.log('TestHTML2')
});
function createBrowserWindow() {
console.log('TestJS1')
const remote = require('electron').remote;
console.log('TestJS2')
const BrowserWindow = remote.BrowserWindow;
const win = new BrowserWindow({
height: 600,
width: 800,
webPreferences: {
nodeIntegration: true
}
});
win.loadFile('./index.html')
win.show()
}
【问题讨论】:
标签: javascript node.js electron