electron窗口切换

-

通过菜单切换

main.js

const { app, BrowserWindow, Menu, MenuItem, shell } = require('electron')
const path = require('path')
// 保持一个对于 window 对象的全局引用,不然,当 JavaScript 被 GC,
// window 会被自动地关闭
var mainWindow = null;

// 当所有窗口被关闭了,退出。
app.on('window-all-closed', function() {
  // 在 OS X 上,通常用户在明确地按下 Cmd + Q 之前
  // 应用会保持活动状态
  if (process.platform != 'darwin') {
    app.quit();
  }
});
// 当 Electron 完成了初始化并且准备创建浏览器窗口的时候
// 这个方法就被调用
app.on('ready', function() {
  // 创建浏览器窗口。
  mainWindow = new BrowserWindow({
     800,
    height: 800,
    // frame: false, // windows下隐藏导航栏
    // titleBarStyle: 'hidden', // mac下隐藏导航栏
    webPreferences: {
      nodeIntegration: true, // 是否启用Node integration. 5.0以后默认值为 false.
      contextIsolation: false, // 设置为false后,才能在渲染进程使用Electron API
      preload: path.join(__dirname, 'preload.js')
    }
  });
});

// 设置系统菜单
// 切换页面的函数
const sendMenuEvent = (url) => {
  mainWindow.webContents.send('change-view', url);
}
const menuTemplate = [
  {
    label: '首页',
    click: async () => {
      //在electron窗口内打开首页
      mainWindow.loadURL(path.join(__dirname, 'index.html'));
    }
  },
  {
    label: '父级',
    submenu: [
      {
          label: 'electron窗口内打开百度',
          click: async () => {
            //在electron窗口内打开百度
            sendMenuEvent('http://www.baidu.com');
          },
      }, 
      {
        label: '默认浏览器打开百度',
        click: async () => {
          //在默认浏览器打开新的窗口
          await shell.openExternal('http://www.baidu.com');
        },
      }
    ]
  }
]
const list = Menu.buildFromTemplate(menuTemplate)
Menu.setApplicationMenu(list);

preload.js

const { ipcRenderer } = require('electron')
// 在electron窗口内切换页面
if(window && window.process && window.process.type === 'renderer') {
  ipcRenderer.on('change-view', (event, url) => {
    window.location.href = url;
  });
}

以上是用electron打开新窗口

下面用js打开新窗口:

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <!-- 安全设置 -->
  <meta http-equiv="Content-Security-Policy" content="default-src 'self' 'unsafe-inline';">
  <title>Document</title>
</head>
<body>
  <script>
    // js切换窗口
    baidu.addEventListener('click', () => {
      window.open('http://www.baidu.com', '_self')
    })
    // 在新窗口打开页面
    baidu2.addEventListener('click', () => {
      window.open('http://www.baidu.com', '_blank')
    })
  </script>
</body>
</html>

效果:

 

-

原文地址:https://www.cnblogs.com/fqh123/p/15782244.html