Electron使用与学习--(页面间的通信)

目录结构:

 

index.js是主进程js。

const electron = require('electron')

const app = electron.app

const BrowserWindow = electron.BrowserWindow

//主进程
const ipc = require('electron').ipcMain;

app.on('ready',function(){
    var mainWindow = new BrowserWindow({
        width: 800,
        height: 600
    })
    mainWindow.loadURL('file://' + __dirname + '/index.html') //主窗口

    mainWindow.openDevTools();

    var presWindow = new BrowserWindow({
        width: 300,
        height: 300,
        show: false
    })

    presWindow.loadURL('file://' + __dirname + '/presWindow.html') //新窗口

    ipc.on('zqz-show',function() {
        presWindow.show()
    })

    ipc.on('hide-pres',function() {
        presWindow.hide()
    })
})

说明:

这里主进程通过ipcMain响应来自index.html(渲染进程ipcRenderer)发出的指令。zqz-show,打开一个窗口
这里主进程通过ipcMain响应来自persWindow.html(渲染进程ipcRenderer)发出的指令。hide-pres,关闭一个窗口
 
index.html
<!DOCTYPE html>
<html>
<head>
    <title>zqz_electron_demo</title>
</head>
<body>
Hi
</body>
<script type="text/javascript">
    require('./app.js')
</script>
</html>

 

app.js

const remote = require('electron').remote;
const Menu = remote.Menu;
const MenuItem = remote.MenuItem;

//渲染进程
const ipc = require('electron').ipcRenderer;

var menu = new Menu.buildFromTemplate([
    {
        label: '菜单',
        submenu: [
            {
                label: '打开新窗口',
                click: function(){
                    ipc.send('zqz-show') //注册的指令。send到主进程index.js中。
                }
            }
        ]
    }
])

Menu.setApplicationMenu(menu);

 

presWindow.html(新窗口页面)

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>presWindow</title>
</head>
<body>

    新窗口

</body>
<script type="text/javascript">
    const ipc = require('electron').ipcRenderer;

    var button = document.createElement('button');
    button.textContent = 'Hide';
    button.addEventListener('click',function(){
        ipc.send('hide-pres') //注册的指令。send到主进程index.js中。
    })
    document.body.appendChild(button)

</script>
</html>

 

效果:

      

点击hide窗口关闭。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值