Ram Kumar
Ram Kumar

Reputation: 848

How to call a function is renderer.js/main.js from web page in electron

Newbie to electron here, I have built a simple web application with React JS and able to view it in a window by calling

window.loadFile('./build/index.html');

Now i would want to call a function located in say renderer.js/main.js which should read file system and return data to the web application.

I have already tried this in renderer.js

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

document.getElementById('#button').addEventListener('click', function (event) {
    //read file contents
    console.log('file contents');
});

But there are 2 issues around here

  1. The control is from the renderer.js, instead i would want the control to be on the web page of React.
  2. The data that is read should be returned back to web page, so that it can be displayed in the web page.

Upvotes: 1

Views: 1228

Answers (3)

tpikachu
tpikachu

Reputation: 4844

You are building your electron renderer using React.

Please check this to clear what main process is and renderer is.

how to communicate between react and electron

This is the answer I posted before. Feel free to check this.

And here is the pre-requirement.

let mainWindow = new BrowserWindow(
  {
    width: 800,
    height: 600,
    webPreferences:{
      nodeIntegration:true
    }
  });

You should enable the nodeIntegration flag when you are creating the BrowserWindow. So that you can use any Nodejs API at your renderer

Upvotes: 0

Andreas Dolk
Andreas Dolk

Reputation: 114817

You should be able to import/require ipcRenderer directly on your react component scripts and maybe load the file on a lifecycle hook. The 'renderer.js' is just one way to execute client side javascript on the (electron-)web page but any other way also does the trick.

If you can't import or require electron from the webapp (I didn't play with the electron-react-boilerplate yet), then you could write a so called preload script, load that when you create the browser window (see that documentation) and put the ipcRenderer on window like so:

const {ipcRenderer} = require('electron')
window.ipcRenderer = ipcRenderer

Then you can access it from the react app.

Upvotes: 1

Alan Darmasaputra
Alan Darmasaputra

Reputation: 468

You could directly use fs inside the event listener

const { ipcRenderer } = require('electron');
const fs = require("fs");

document.getElementById('#button').addEventListener('click', function (event) {
  console.log(fs.readFileSync("some/file/path", "utf8"));
});

Electron exposes full access to Node.js both on main and renderer process

https://www.electronjs.org/docs/tutorial/application-architecture#using-nodejs-apis

Upvotes: 0

Related Questions