electron WebView向子页面传递数据的方法

我用到了2种方式, 

1.和浏览器里一样通过 URL或是llocalstorage 等等

2.我也是刚接触electron 没几天, 就查到了一种方式  通过webContents监听did-finish-load,然后send().

文档上是这么讲的

Event: 'did-finish-load'

当导航完成时发出事件,onload 事件也完成.

 

然后在这个监听里面写  webContents.send();

webContents.send(channel[, arg1][, arg2][, ...])

  • channel String
  • arg (可选)

通过 channel 发送异步消息给渲染进程,你也可发送任意的参数.参数应该在 JSON 内部序列化,并且此后没有函数或原形链被包括了.

渲染进程可以通过使用 ipcRenderer 监听 channel 来处理消息

 

 function showDetailPage(index) {
 	try {
        let win = new BrowserWindow({
                     800,
                    height: 500,
                    show: false,
                    maximizable: false,
                    minimizable: false,
                    resizable: false,
                    useContentSize: true,
                    //parent: currentWindow,
                    modal: false
                });
				
        		let dataJson=JSON.stringify(dataSource.data());
                // win.webContents.openDevTools();
                win.on('closed', function () { win = null })
                win.loadURL('file://' + __dirname + '/AnnouncementDetail.html?index='+index)//指定渲染的页面
                win.webContents.on('did-finish-load', function(){
			        win.webContents.send('dataJsonPort', dataJson);
			    });
                win.show();//打开一个窗口
  				win.webContents.openDevTools();

        // Open in Windows Client.
        //bound.openReportDetailPage(JSON.stringify(dataSource.data()), index);
      } catch(e) {

        console.log(e);
      }
    }

 这里发送了数据 dataJson,在子页面用

     remote,
        ipcRenderer
    } = require('electron');
    const BrowserWindow = require('electron').remote.BrowserWindow;
    const currentWindow = remote.getCurrentWindow();
        pIndex = getQueryUrlString('index');
    ipcRenderer.on('dataJsonPort', function(event, message) { // 监听父页面定义的端口
        initTable(message, pIndex); 把数据传给函数 initTable
    });

  

我也刚接触这个框架, 如果有不对的地方,还请大家多多交流

 

 

原文地址:https://www.cnblogs.com/xuhongli/p/7076533.html