当涉及到HTML / JS时,我真的是一个初学者,并且我正在尝试构建一个基于Electron的简单多页应用程序。由于页面的布局和整体功能截然不同,因此我读到我应该避免使用有据可查的单页面应用程序方法。我想使用按钮从一页移动到另一页,但被卡住了。我正在主页上创建按钮,但是在加载其他页面时无法创建其他按钮。 因此,使用2个按钮创建了“开始”页面,这将打开Page2和“开始”页面,但是在新创建的窗口中没有按钮出现。在重新加载“开始”页面时,我希望出现两个相同的按钮。另外,由于page2指向与“开始”页面相同的脚本,所以我希望看到2个按钮出现在page2上。
在代码下方添加:
package.json:
{
"name": "multiple-windows3",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "electron ."
},
"author": "",
"license": "ISC"
}
Index.js
const { app, BrowserWindow,ipcMain } = require('electron')
function createWindow () {
let win = new BrowserWindow({width: 800,height: 600, webPreferences: {
nodeIntegration: true}
})
win.loadFile('index.html')
}
app.on('ready', createWindow)
ipcMain.on('open-new-window', (event, fileName) => {
let win = new BrowserWindow({width:800, height:600})
win.loadURL(`file://${__dirname}/` + fileName + `.html`)
})
Index.html
<body>
<h1>Start</h1>
<script src="home.js"></script>
</body>
Home.js
const remote = require('electron').remote
const main = remote.require('./index.js')
const {ipcRenderer} = require('electron');
var button = document.createElement('button')
button.textContent = 'Open Window'
button.addEventListener('click', () => {
ipcRenderer.send('open-new-window', 'page2');
}, false)
document.body.appendChild(button)
var button2 = document.createElement('button')
button2.textContent = 'Open Window2'
button2.addEventListener('click', () => {
ipcRenderer.send('open-new-window', 'index');
}, false)
document.body.appendChild(button2)
page2.html
<body>
<h1>Page2</h1>
<script src="home.js"></script>
</body>
谢谢