Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get DOM tree from BrowserWindow in electron app?

I would like to get data from one process to another in electron and I can't figure out how to do this. I have the following code:

// I create a new browser window to load url
var win = new BrowserWindow({ width: 800, height: 600, show: false });

win.loadURL('chrome://gpu');
win.webContents.on('dom-ready', function() {
  console.log("dom is ready");
});

// Here I want to get content of the loaded page and log it.

I tried ipc, but I can figure out how to use it.

like image 859
Bill Lumbert Avatar asked Jan 26 '16 16:01

Bill Lumbert


1 Answers

If you only want to log the contents you can write them to the Main process stdout directly using Electron's remote.process directly from the Renderer, but if you want to send the contents to the Main process IPC is probably the best way (you could also use files, sockets etc.).

Here is a very quick example of how you could do this all from your main.js file (but I'd suggest to use a separate file for the Renderer code and require it using BrowserWindow's 'preload' option, this is just for illustrative purposes).

var electron = require('electron');
var ipc = electron.ipcMain;
var BrowserWindow = electron.BrowserWindow;

var win = new BrowserWindow({ width: 800, height: 600, show: false });

win.webContents.on('dom-ready', () => {
  win.webContents.executeJavaScript(`
    require('electron').ipcRenderer.send('gpu', document.body.innerHTML);
  `);
});

ipc.on('gpu', (_, gpu) => {
  console.log(gpu)
})

win.loadURL('chrome://gpu');
like image 103
inukshuk Avatar answered Nov 10 '22 22:11

inukshuk