nobsoph
nobsoph

Reputation: 23

Is there a way to pass data from Electron to the URL in the webview?

I have an Electron app, inside the app has a webview to load my app UI. For some reason, I need to separate the Electron frame and UI and runs as two apps. UI sits in the cloud and Electron use webview to display the UI.

My UI need a piece of data from the Electron to continue running, so I'm looking for a way that either the Electron can give a signal and then UI can do something like addEventListener to wait for the signal, or the UI can somehow access the Electron to check if that piece of data is not null.

I tried ipcRender and ipcMain, but this method only works inside the Electron, the data I want to send from the Electron doesn't get pass to the UI.

Does anyone have similar experience and willing to share your solution? please and much appreciate.

Upvotes: 0

Views: 1696

Answers (2)

0xENDER
0xENDER

Reputation: 109

You can use the executeJavaScript function.

<webview>.executeJavaScript(`receiveMessage("My message!")`);

And in your <webview>, there would be a function that will receive the message:

function receiveMessage(message){
    //Do something with `message`
}

Upvotes: 2

nobsoph
nobsoph

Reputation: 23

After days of research and test my code, I finally got it to work!

Thanks to this post helps me understand the ipcRender and ipcMain issue I was having. To whoever wants to do a similar thing, here's how I do it.

In the UI code that sits in the cloud, add following code:

const ipcRenderer = window.require('electron').ipcRenderer;
ipcRenderer.send('notes', "the msg from the cloud UI");

In the main.js of the Electron, add following code:

import { ipcMain } from 'electron'

//inside the createWindow function
ipcMain.on('notes', function(event, data) {
   console.log('notes: ', data)
   mainWindow.webContents.send('notes2', data) //send message back to webview
})

In the webview tag of the Electron, add following code:

<webview src={the_UI_url}
    nodeIntegration
  preload="file:{the_exact_path_of_preload.js}/preload.js"></webview>

nodeIntegration must be included, otherwise, you'll get the error window.require is not a function in the UI code

In the preload.js, add following code:

const { ipcRenderer } = require('electron')

ipcRenderer.on('notes2', function(event, data) {
    console.log('notes2: ', data);
});

After all these code added, I successfully see "the msg from the cloud UI" in the Electron console.

Upvotes: 1

Related Questions