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窗口關閉。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM