Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Electron: Communicate between BrowserWindow and rendered URL (nodeIntegration: false)

I've spent about an hour reading gist after repo after blog post, but can't seem to figure out how to do do this.

I have a BrowserWindow instance loading a URL (that I control), with nodeIntegration: false.

From the main process, I'd like to communicate with the rendered URL. I'm getting confused between preload scripts, BrowserWindow.send and executeJavascript paradigms.

The data I want to send is very large (eg. file uploads between 50kb and 10mb).

What's the best way to do this? Any any examples/tutorials you may know about would be helpful. Thanks!

like image 801
onassar Avatar asked Apr 30 '18 14:04

onassar


1 Answers

main.js

const path = require('path')
const electron = require('electron')
const { app, BrowserWindow, ipcMain } = electron

const window = new BrowserWindow({
  minWidth: 1200,
  minHeight: 700,
  autoHideMenuBar: true,
  resizable: true,
  show: false,
  scrollBounce: true,
  webPreferences: {
    preload: path.join(__dirname, 'preload.js'),
  }
})
window.webContents.loadURL('https://xxx.xxx.com') // load your web page
ipcMain.on('ping', (event, msg) => {
  console.log(msg) // msg from web page
  window.webContents.send('pong', 'hi web page') // send to web page
})

preload.js

const { ipcRenderer } = require('electron');
function init() {
  // add global variables to your web page
  window.isElectron = true
  window.ipcRenderer = ipcRenderer
}

init();

your web page

<script>
  if (window.isElectron) {
    window.ipcRenderer.send('ping', 'hello main')
    window.ipcRenderer.on('pong', (event, msg) => console.log(msg))
  }
</script>
like image 166
feedpanda Avatar answered Oct 17 '22 17:10

feedpanda