Electron經過 BrowserWindow 和 webContents 模塊實現渲染進 程和渲染進程的通訊

ipcmain.jshtml

var {ipcMain,BrowserWindow} =require('electron');


var path=require('path');

var win=null;

//接收到廣播
ipcMain.on('openWindow',function(event,aid){
        


    //調用 BrowserWindow打開新窗口
    win=new BrowserWindow({

        width:400,
        height:300,
        webPreferences:{
            nodeIntegration: true
        }
    })
    win.loadURL(path.join('file:',__dirname,'../news.html'));
    
    //開啓新窗口的調試模式
    win.webContents.openDevTools();


    //經過win.webContents.send把當前數據廣播給 news進程

    win.webContents.on('did-finish-load',function(){

        win.webContents.send('toNews',aid);
    })






    win.on('closed',()=>{

        win=null;
    })


})

new.jsnode

//獲取localStorage的數據
var {ipcRenderer} =require('electron');


ipcRenderer.on('toNews',function(event,aid){

    console.log(aid);
})

openwidow.jsweb

var {ipcRenderer} =require('electron');



var btn=document.querySelector('#btn');

//渲染進程無法直接調用主進程中的模塊,可是咱們能夠經過 electron中的remote模塊間接的調用主進程中的模塊


btn.onclick=function(){
    // alert('點擊了');



    var aid='123456';

    ipcRenderer.send('openWindow',aid);



}

new.jselectron

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
    
        body{
            background: orange;
        }
    </style>
    
</head>
<body>
   news頁面

    <br>

    哈哈哈

    <script src="renderer/news.js"></script>   
</body>
</html>

index.htmlide

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>

    <style>    
        .content{

            width: 100%;

            height: 400px;

            background: orange;


            overflow-y: auto;
        }
    </style>
  
</head>
<body>
       
    <button id="btn">
        打開新窗口
    </button>
    

    <script src="renderer/openWindow.js"></script>   

</body>
</html>
相關文章
相關標籤/搜索