例子
html页面添加事件
<ul>
<li><button onclick="openNewWindow()">new BrowserWindow</button></li>
<li><button onclick="windowOpen()">window.open</button></li>
<li><button οnclick="οnclick="changePage('./pages/openWindow/openWindowIndex.html')"">切换页面</button></li>
</ul>
切换页面 和 打开窗口的方法
window.location.href
切换窗口内容window.open
打开新的窗口new BrowserWindow
打开新的窗口
const path = require('path')
// 当前页面做切换
function changePage (pageUrl) {
window.location.href = pageUrl
}
// 使用 window.open 打开一个新的窗口
function windowOpen () {
// window.open 来创建一个新的窗口时候,将会创建一个 BrowserWindow 的实例,并且将返回一个标识,这个界面通过标识来对这个新的窗口进行有限的控制.
// window.open(url[, frameName][, features])
// url String
// frameName String (可选)
// features String (可选)
let url = path.join("file://",__dirname,"./pages/introduce.html");
let winObj = window.open(url)
console.log("winObj : " + winObj)
}
// 创建一个 BrowserWindow 对象,打开一个新的窗口
function openNewWindow() {
// __dirname 代表的是html文件的路径,不是js的路径;E:\gitcode\electron-study\src
console.log(__dirname);
const modalPath = path.join("file://",__dirname,"./pages/introduce.html");
let win = new BrowserWindow({ width: 400, height: 275 });
win.on("resize", updateReply);
win.on("move", updateReply);
win.on("close", function() {
win = null;
});
win.loadURL(modalPath);
win.show();
function updateReply() {
const manageWindowBtn = document.getElementById("infoContainer");
const message = `Size: ${win.getSize()} Position: ${win.getPosition()}`;
manageWindowBtn.innerHTML = message;
}
}
如果要使用 require(‘path’), 则需要开启nodejs环境,否则无法使用
打开新窗口需要 —— 开启nodejs环境
const { app, BrowserWindow, BrowserView, globalShortcut } = require('electron')
var mainWindow = null // 声明要打开的主窗口
app.on('ready', () => {
// 设置窗口的高度和宽度
mainWindow = new BrowserWindow({
width: 800,
height: 800,
frame: false, // 是否有边框
webPreferences: {
nodeIntegration: true, // 设置开启nodejs环境
enableRemoteModule: true // enableRemoteModule保证renderer.js可以可以正常require('electron').remote,此选项默认关闭且网上很多资料没有提到
}
})
// 窗口加载的文件
mainWindow.loadFile('./src/index.html')
// 开启渲染进程中的调试模式
mainWindow.webContents.openDevTools()
// 监听窗口关闭 销毁引用
mainWindow.on('closed', () => {
mainWindow = null
})
})
-
设置开启nodejs环境
webPreferences.nodeIntegration: true
-
enableRemoteModule保证renderer.js可以可以正常require(‘electron’).remote
webPreferences.enableRemoteModule: true
-
设置窗口是没有边框的
frame: false, // 是否有边框