Electron js not rendering react built web app - javascript

My react web app runs fine in development mode, it also works fine when I host the build version from express server. But when I try to render it from electron js it does not render anything.
In console, it says Failed to load resource: net::ERR_FILE_NOT_FOUND main.8d9a4060.chunk.css:1 Failed to load resource: net::ERR_FILE_NOT_FOUND and I cant understand what is causing the issue.
my electron code is like this:-
const { app, BrowserWindow } = require('electron');
const path = require('path');
if (require('electron-squirrel-startup')) {
app.quit();
}
const createWindow = () => {
// Create the browser window.
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true
}
});
mainWindow.loadFile(path.join(__dirname, 'build', 'index.html'));
mainWindow.webContents.openDevTools();
};
app.on('ready', createWindow);
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});

try 'loadURL' instead 'loadFile'
https://www.electronjs.org/docs/api/browser-window

Related

require module inside preload script in electron

I'm building an app with electron react and MySQL, I'm stuck in preload script where i want to make my db instance available in render-er process, i got the following error
Error: module not found: ./config/db in console.
this happening when i try to require a module inside preload script.
const { app, BrowserWindow } = require("electron");
const path = require("path");
const isDev = require("electron-is-dev");
const dotenv = require("dotenv");
//load .env
dotenv.config();
function createWindow() {
// Create the browser window.
const mainWindow = new BrowserWindow({
title: "Electron",
minWidth: 800,
minHeight: 600,
webPreferences: {
preload: path.join(__dirname, "preload.js"),
devTools: isDev,
},
});
//get url dependig on envirement (dev/prod)
const url = isDev
? `http://localhost:${process.env.PORT}/`
: `file://${path.join(__dirname, "../../dist/react/index.html")}`;
// load the url
mainWindow.loadURL(url);
// Open the DevTools.
isDev && mainWindow.webContents.openDevTools();
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
createWindow();
app.on("activate", function () {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (BrowserWindow.getAllWindows().length === 0) createWindow();
});
});
// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on("window-all-closed", function () {
if (process.platform !== "darwin") app.quit();
});
// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
require("./handlers");
preload
const { contextBridge, ipcRenderer } = require("electron");
const { db } = require("./config/db");
contextBridge.exposeInMainWorld("mainApi", {
db,
});
Since Electron v20.0.0, the sandbox parameter defaults to true (according to the list of Breaking Changes)
One of the side effects of the sandbox attribute is that it can only require a few things:
A require function similar to Node's require module is exposed, but can only import a subset of Electron and Node's built-in modules:
electron (only renderer process modules)
events
timers
url
To disable sandboxing, just add sandbox: false to your webPreferences on window creation:
// ...
// Create the browser window.
const mainWindow = new BrowserWindow({
title: "Electron",
minWidth: 800,
minHeight: 600,
webPreferences: {
preload: path.join(__dirname, "preload.js"),
devTools: isDev,
sandbox: false, // fixes require() in preloader
},
});
// ...

Socket.IO with Electron app to send front end data to back end?

I've seen a lot of examples on how to implement socket.io, but none that I can find that maintain the structure of the electron app in the process (typically it's just using express instead). I was wondering how I could implement socket.io with a basic electron app? Here's my boiler plate code:
Client.js file:
const socket = io("http://localhost:3000");
// When client successfully connects to server
socket.on("connect", () => {
console.log(`Connected to server`);
});
// Receive message from backend
socket.on("message", data => {
console.log(`Server: ${data}`);
});
I'd like to receive the above socket.on actions in my electron code if possible (while keeping things inside the app as opposed removing the app code and doing this by opening the browser)
Electron.js boilerplate:
const { app, BrowserWindow } = require('electron');
const path = require('path');
// Handle creating/removing shortcuts on Windows when installing/uninstalling.
if (require('electron-squirrel-startup')) {
// eslint-disable-line global-require
app.quit();
}
const createWindow = () => {
// Create the browser window.
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
});
// and load the index.html of the app.
mainWindow.loadFile(path.join(__dirname, 'index.html'));
// Open the DevTools.
mainWindow.webContents.openDevTools();
};
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow);
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
Any help is appreciated!

while running JS app uncaught exception error require is not defined occurs [duplicate]

This question already has answers here:
Client on Node.js: Uncaught ReferenceError: require is not defined
(11 answers)
Closed 1 year ago.
i gone through a video link to create a simple java script based app using electron. https://www.youtube.com/watch?v=TnXz_nnQZrwI
While trying to create an app i got the following error even though i enable the nodeIntegration to true
index.html:12 Uncaught ReferenceError: require is not defined
at index.html:12
I don't know how to resolve it plz help
This is my js and Html files
my index.js file
const { app, BrowserWindow } = require('electron');
const os = require('os-utils');
const path = require('path');
// Handle creating/removing shortcuts on Windows when installing/uninstalling.
if (require('electron-squirrel-startup')) { // eslint-disable-line global-require
app.quit();
}
const createWindow = () => {
// Create the browser window.
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences:{
nodeIntegration: true
}
});
// and load the index.html of the app.
mainWindow.loadFile(path.join(__dirname, 'index.html'));
// Open the DevTools.
mainWindow.webContents.openDevTools();
os.cpuUsage(function(v){
console.log('CPU Usage (%): '+ v*100);
mainWindow.webContents.send('CPU',v*100);
console.log('Mem Usage (%): '+ os.freememPercentage()*100);
mainWindow.webContents.send('Mem',os.freememPercentage()*100);
console.log('Total Mem (GB): '+ os.totalmem()/1024);
mainWindow.webContents.send('Total-Mem',os.totalmem()/1024);
});
};
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow);
// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', () => {
// On OS X it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and import them here.
my index.html file
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello World!</title>
<link rel="stylesheet" href="index.css">
</head>
<body>
<h1>💖 Hello World!</h1>
<p>Welcome to your Electron application.</p>
<script>
const electron = require('electron');
const ipcRenderer = electron.ipcRenderer;
ipcRenderer.on('CPU',(event,data)=>{
console.log('CPU %' + data);
});
ipcRenderer.on('Mem',(event,data)=>{
console.log('Mem Usage %' + data);
});
ipcRenderer.on('Total-Mem',(event,data)=>{
console.log('Total Mem (GB)' + data);
});
</script>
</body>
</html>
For Electron >= 12, nodeIntegration: true won't work without contextIsolation: false.
https://www.electronjs.org/docs/breaking-changes#default-changed-contextisolation-defaults-to-true
Alternatively, if you do not want to take any security risks by setting nodeIntegration: true, you can make ipcRenderer available to your renderer process by creating a global variable in a "preload-file" that is called just before your renderer window is created.
In main.js create your main renderer window like this:
function createWindow () {
win = new BrowserWindow({
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
contextIsolation: false
}
})
win.loadFile('index.html')
}
The important part is preload: path.join(__dirname, 'preload.js').
In your preload.js you create a global variable ipcRenderer like this:
process.once('loaded', () => {
global.ipcRenderer = electron.ipcRenderer;
});
Then ipcRenderer can be used in your renderer process' html code just like that:
<script>
...
ipcRenderer.send(...);
...
</script>

How to grant permission to audio in electron app in Windows?

I'm trying to implement speech recognition into the electron application. The solution works in chrome browser, but does not work in electron. The application stops listening immediately - it probably has no microphone permission. How to grant permissions?
index.js
const electron = require('electron');
const url = require('url');
const path = require('path');
const { app, BrowserWindow, ipcMain } = electron;
let mainWindow;
ipcMain.on('close-me', (evt, arg) => {
app.quit()
})
app.on('ready', () => {
mainWindow = new BrowserWindow({
transparent: true,
frame: false,
webPreferences: {
nodeIntegration: true,
webviewTag: true
}
});
mainWindow.loadURL(url.format({
pathname: path.join(__dirname, 'web/index.html'),
protocol: 'file',
slashes: true
}));
mainWindow.webContents.openDevTools();
mainWindow.setFullScreen(true);
});
index.html
<!doctype html>
<html lang="en">
<head>
<title></title>
<link rel="stylesheet" href="styles/style.css">
</head>
<body>
<div class="container">
<button id="rec"> rec</button>
<button id="endrec"> end</button>
</div>
<script src="scripts/speech.js"></script>
</body>
</html>
speech.js
const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
const recognition = new SpeechRecognition();
recognition.lang = 'pl-PL';
const rec = document.querySelector('#rec');
const endrec = document.querySelector('#endrec');
recognition.onstart = function () {
console.log('I started');
}
recognition.onend = function () {
console.log('I finished');
}
recognition.onresult = function () {
console.log('Take what I recorded');
console.log(event);
const current = event.resultIndex;
const transcript = event.results[current][0].transcript;
console.log(transcript);
}
rec.addEventListener('click', () => {
recognition.start();
console.log('You clicked me');
})
endrec.addEventListener('click', () => {
recognition.stop();
})
I've also tried solutions with
webview.addEventListener('permissionrequest', function (e) {
if (e.permission === 'media') {
e.request.allow();
}
});
and
navigator.webkitGetUserMedia({ audio: true })
UPDATE
I found a reason to stop recognizing - error - network
I think you'll want to use the setPermissionRequestHandler on your session, like this:
const electron = require('electron');
const url = require('url');
const path = require('path');
const {
app,
BrowserWindow,
ipcMain,
session
} = electron;
let mainWindow;
ipcMain.on('close-me', (evt, arg) => {
app.quit()
})
app.on('ready', () => {
mainWindow = new BrowserWindow({
transparent: true,
frame: false,
webPreferences: {
nodeIntegration: true,
webviewTag: true
}
});
mainWindow.loadURL(url.format({
pathname: path.join(__dirname, 'web/index.html'),
protocol: 'file',
slashes: true
}));
mainWindow.webContents.openDevTools();
mainWindow.setFullScreen(true);
session.fromPartition("default").setPermissionRequestHandler((webContents, permission, callback) => {
let allowedPermissions = ["audioCapture"]; // Full list here: https://developer.chrome.com/extensions/declare_permissions#manifest
if (allowedPermissions.includes(permission)) {
callback(true); // Approve permission request
} else {
console.error(
`The application tried to request permission for '${permission}'. This permission was not whitelisted and has been blocked.`
);
callback(false); // Deny
}
});
});
I've faced similar problem myself and found out that google doesn't provide speechAPI for CLI based apps like electron. Your best bet is to use either Google Cloud Speech API or any third-party API like Microsoft Cognitive Service.
Are you testing on MacOS? I faced a similar issue in my MBP, and below check solved the issue -
systemPreferences.askForMediaAccess(microphone)
See the Electron doc reference for additional details.

Electron app runs without any errors however the window does not open or show in task manager

I am building an electron app. The app runs without any errors but does not open. I am running windows 7 on a 32 bit machine. My main.js file looks like this:
const {app, BrowserWindow} = require('electron');
const path = require('path');
const url = require('url');
// Initialize window
let win;
function createWindow() {
win = new BrowserWindow({
width: 800,
height: 600,
icon: __dirnaname+ '/assets/images/icon.jpg'
});
// Load Window
win.loadUrl(url.format({
pathname: path.join(__dirname, './index.html'),
protocol: 'file',
slashes: true
}));
// Close window
win.on('closed', () =>{
win = null;
});
//Run Create Window Function
win.on('ready', createWindow);
//Check Mac OS platform
app.on('all-window-closed', () => {
if(process.platform !== 'darwin') {
app.quit();
}
});
};
This line is wrong
win.on('ready', createWindow);
you meant
app.on('ready', createWindow);
outside of createWindow's scope. Like this:
function createWindow() {
...
};
app.on('all-window-closed', () => {
...
});
app.on('ready', createWindow);
I had the same problem after I upgraded electron from v3.x to v8.x it started working

Categories

Resources