2018年的文章移至github上,点我去!2018年的文章移至github上,点我去!2018年的文章移至github上,点我去!

Fork me on GitHub

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窗口关闭。

 

posted on 2016-06-04 10:49  qize  阅读(23258)  评论(6编辑  收藏  举报

导航