Ash Babayan
Ash Babayan

Reputation: 9

Js file becomes non-functional as soon as I require ipcRenderer

I was testing the ipcRenderer process for my project and I got to a point where, in my javascript file, I require ipcRenderer:

const { ipcRenderer } = require('electron')

In my HTML file, I have declared:

 <script type="javascript" src="myjavascriptfile.js"></script>

As soon as I do this, any code, function or anything declared in my JS file just doesn't work without any errors in the console or any other notifications.

I already set nodeIntegration: true and contextIsolation: false in my main.js that is the main file for Electron.

If however there is any other solution to the issue, my purpose is to get a textarea value and id of the line, send it to an object, and save it as a JSON file. I am using ipcRenderer to send the values to ipcMain and there is fs from node to create the file. However as described above, I am not able to get this to work.

This is just the example as of how I am wanting to use, this is not the final code of course, but if I get this to work, I will process the other stuff:

const ipcRenderer = require('electron').remote

const Savebtn = document.getElementById("SaveSong")
let song = ['text', 'id']

Savebtn.addEventListener("click", () => {
  ipcRenderer.send('save', song)
  console.log(song)
})

Upvotes: 0

Views: 79

Answers (1)

Arkellys
Arkellys

Reputation: 7780

First things first, enabling nodeIntegration and/or disabling contextIsolation will create security vulnerabilities into your app. Don't do that unless you have good reasons and that you are sure of what you are doing. Next, the remote module has been deprecated since Electron 12, and removed since Electron 14, you should not (and don't need to) use it.

When everything is configured to be secure, you need to use a preload file in order to use IPC. For example:

Main

new BrowserWindow({
  webPreferences: {
    nodeIntegration: false, // This is default
    contextIsolation: true, // This is default
    preload: path.join(__dirname, 'preload.js') // Path to your preload file
  }
});

Preload

const { contextBridge, ipcRenderer  } = require("electron");

contextBridge.exposeInMainWorld("electronAPI", {
  saveSong: (song) => ipcRenderer.send("save", song)
});

Renderer

Savebtn.addEventListener("click", () => {
  window.electronAPI.saveSong(song);
});

Make sure you are not using require in your renderer process and that you only import into your preload what's available with sandboxing (otherwise you'll get more errors).

You can read more about security in the docs, and find more working examples also in the docs.

Upvotes: 0

Related Questions