我正在使用electronic和socket.io设置GUI服务器应用程序。我无法获得index.html
中的onclick按钮来运行startServer()
中的server.js
功能。我需要帮助]
我已经尝试使用ID和事件监听器来运行该功能。非常感谢您的帮助,谢谢。
main.js:
const electron = require('electron')
const app = electron.app
const BrowserWindow = electron.BrowserWindow
const path = require('path')
let mainWindow
function createWindow() {
mainWindow = new BrowserWindow({
height: 500,
width: 700,
frame: false,
resizable: false,
webPreferences: {
nodeIntegration: true
}
});
// Load html into window
mainWindow.loadURL('file://' + __dirname + '/app/index.html');
mainWindow.on('closed', () => {
mainWindow = null
})
}
// Listen for app to be ready
app.on('ready', createWindow)
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', () => {
if (mainWindow === null) {
createWindow()
}
})
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="app.css">
</head>
<body>
<script>server.js</script>
<div class="disable-highlight">
<h1>DNPS
</h1>
</div>
<input type="button" onclick="startServer()" value="Start Server" />
<script>
require('./server.js')
</script>
</body>
</html>
server.js:
const log = require('electron-log')
function startServer() {
// Load Socket.io
var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.send('<h1>Hello world</h1>');
});
io.on('connection', function(socket){
log.info('a user connected')
});
http.listen(3000, function(){
log.info('listening on *:3000');
});
};
[经过反复摆弄之后,我发现document.getElementById
对我有用。
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="app.css">
</head>
<body>
<div class="disable-highlight">
<h1>DNPS</h1>
<input id="startBtn" type="button" value="Start Server"/>
<script>require('./server.js')</script>
<table class='center'>
<td id="consoleLog">
</td>
</table>
</div>
</body>
</html>
server.js:
const log = require('electron-log')
// Load Socket.io
const app = require('express')();
const http = require('http').createServer(app);
const io = require('socket.io')(http);
var tempLog = ''
function pushLog() {
document.getElementById('consoleLog').innerHTML = tempLog
}
document.getElementById('startBtn').onclick = function() {
app.get('/', function(req, res){
res.sendFile(__dirname + '/output/index.html');
});
log.info('pushing index.html to localhost')
tempLog += 'pushing index.html to localhost<br>'
io.on('connection', function(socket){
tempLog += 'a user connected<br>'
log.info('a user connected<br>')
pushLog()
});
http.listen(3000, function(){
tempLog += 'listening on *:3000<br>'
log.info('listening on *:3000');
pushLog()
});
};