【发布时间】:2021-11-23 08:37:22
【问题描述】:
长话短说,我正在开发一个通过本地网络发送命令的单页应用程序。测试 Electron JS,我什至无法获得一个简单的按钮来工作。我觉得我并没有以某种方式将 main.js 和 index.js 之间的逻辑联系起来,但对于我的一生,我无法找出正确的方法来做到这一点。我什至在 index.js 和 main.js 和 index.html 中设置了断点,但是除了 main.js 中的断点之外,没有一个断点被击中。我在 preload.js 文件中放置了一个简单的函数,并且该函数被正确调用,但我试图附加到位于 index.html 和 index.js 中的按钮的那个函数甚至从未被点击。很多被注释掉的代码是我想记住的东西,或者是我注意到一种不同的创建方法,只是想试试看是否有效。如果有人有任何答案或指导,将不胜感激! :D
下面是我的 main.js
//#region ---for dev only | hot reload
try {
require('electron-reloader')(module)
} catch (_) {}
//#endregion
const electron = require('electron');
const {app, BrowserWindow, Menu} = require('electron');
const path = require('path');
const ipcMain = electron.ipcMain;
//#region globals
const SRC_DIR = '/src/'
const IMG_DIR = '/assets/images'
//#endregion
function createWindow () {
const win = new BrowserWindow({
width: 800,
height: 600,
//frame: false,
webPreferences: {
contextIsolation: true,
preload: path.join(__dirname, 'preload.js')
}
});
//Used to auto open dev tools for debugging
//win.openDevTools();
win.loadFile('src/index.html');
// win.loadURL(url.format({
// pathname: path.join(__dirname, 'index.html'),
// protocol: 'file',
// slashes: true
// }));
}
app.whenReady().then(() => {
//nativeTheme.shouldUseDarkColors = true;
createWindow();
})
//closes app processes when window is closed
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') app.quit();
})
var menu = Menu.buildFromTemplate([
{
label: 'Menu',
submenu: [
{label: 'Edit'},
{type: 'separator'},
{
label: 'Exit',
click() {
app.quit();
}
}
]
}
])
Menu.setApplicationMenu(menu);
这里是 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>Ecas Software</title>
<link rel="stylesheet" href="index.css">
</head>
<body>
<p id="myText">Let's get started :)</p>
<button id="myBtn">Change Text</button>
<script type="text/javascript" src="./index.js" ></script>
</body>
</html>
最后是我的 index.js(也就是我的第一个也是唯一一个渲染器?)
const electron = require('electron');
const chgBtn = document.getElementById('myBtn');
function replaceText(selector, text){
const element = document.getElementById(selector);
if (element) element.innerText = text;
}
chgBtn.onclick = function() {
replaceText('myText', 'no boom...');
}
// chgBtn.addEventListener('click', function(){
// // if (document.getElementById('myText').innerText == 'boom'){
// // replaceText('myText','no boom...');
// // } else {
// // replaceText('myText','boom');
// // }
// document.alert("working function");
// });
//chgBtn.addEventListener('click', replaceText('myText','no boom...'));
【问题讨论】:
-
尝试在浏览器窗口中将
contextIsolation设置为false,然后将nodeIntegration设置为true
标签: javascript html node.js electron