构建我的第一个电子应用程序,我希望工作流程如下:
mainWindow打开 - >用户点击'打开'按钮 - >第二个窗口打开 - >用户输入输入/命中提交 - > mainWindow打开备份显示用户输入
我的app.on('ready'
下面是main.js
}。应用程序启动(win.loadURL
)工作正常,open-new-window
事件也是如此。奇怪的是input-broadcast
。
当用户在第二个窗口中输入输入时,主窗口将重新打开。但是,console.log
中的input-broadcast
中的文字未显示,而input-received
永远不会在主窗口的渲染器中触发。
不确定我做错了什么,但我也可能使用了错误的设计模式。任何帮助将不胜感激!
main.js
const {app, BrowserWindow, ipcMain, remote} = require('electron');
const url = require('url');
const path = require('path');
const countdown = require('./countdown');
let win;
const windows = [];
app.on('ready', () =>{
console.log('app ready');
ipcMain.on('open-new-window', () =>{
console.log('trying to open window');
win.loadURL(url.format({
pathname: path.join(__dirname, 'enterValue.html'),
protocol: 'file:',
slashes: true
}));
});
ipcMain.on('input-broadcast', (evt, data) =>{
console.log('input-broadcast happened in main');
win.webContents.send('input-received', data);
win.loadURL(url.format({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file:',
slashes: true
}));
});
win = new BrowserWindow({width: 800, height: 600});
win.loadURL(url.format({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file:',
slashes: true
}));
win.on('closed', () =>{
console.log('closed');
win = null;
});
})
renderer.js(与index.html相关联)
console.log('from renderer1');
const {ipcRenderer} = require('electron');
document.getElementById('start').addEventListener('click', ()=>{
ipcRenderer.send('open-new-window');
console.log('window button clicked');
});
ipcRenderer.on('open-new-window', (evt, count) =>{
document.getElementById('userInput').innerHTML(count);
});
ipcRenderer.on('input-received', (evt, data) =>{
console.log('input received');
console.log(evt);
console.log(data);
});
renderer2.js(与用户enterValue.html相关联)
console.log('from renderer2');
const {ipcRenderer} = require('electron');
document.getElementById('submitButton').addEventListener('click', (evt, input)=>{
var input = document.getElementById('randomInput').value;
ipcRenderer.send('input-broadcast', input);
});
的index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello World!</title>
</head>
<body>
<h1>Hello World!</h1>
<p>Your input was <span id="userInput"></span><p>
<button id="start">Open</button>
<script>require('./renderer')</script>
</html>
enterValue.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p>Enter a name</p>
<input type="text" id="randomInput" placeholder="enter a value"/>
<button id="submitButton">Submit</button>
<script>require('./renderer2.js')</script>
</body>
</html>
答案 0 :(得分:1)
将输入发送回renderer.js
时,您的通话顺序不正确。你打电话
win.webContents.send('input-received', data)
当index.html
尚未重新加载到win
时!
要解决此问题,您应该交换呼叫并确保在发送ipc消息时内容已准备就绪
ipcMain.on('input-broadcast', (evt, data) => {
console.log('input-broadcast happened in main')
win.loadURL(url.format({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file:',
slashes: true
}))
win.webContents.once('dom-ready', () => {
win.webContents.send('input-received', data)
})
})