I recently went back to an old project and updated my electron version. I found online that electron now requires you to add in nodeIntegration: true in order to be able to import electron in your render process. I added this in as seen below, however, I am getting the following error after doing so and am unsure how to resolve this.
// Module Imports
const {app,BrowserWindow,dialog,ipcMain,remote} = require('electron')
var handlers = require('./routelist.js');
var dns = require('dns').promises;
var path = require('path');
var Connection = require('tedious').Connection;
var sql = require('sequelize');
var axios = require('axios');
let win
function createWindow () {
win = new BrowserWindow({webPreferences: {nodeIntegration: true}, width: 1730, height: 900, frame: false})
win.loadFile('./render/index.html')
win.webContents.openDevTools()
win.on('closed', () => {
win = null
})
}
app.on('ready', function() {
createWindow()
});
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', () => {
if (win === null) {
createWindow()
}
})
Error:
Uncaught (in promise) TypeError [ERR_INVALID_ARG_TYPE]: The "id" argument must be of type string. Received type object
at validateString (internal/validators.js:112)
at Module.require (internal/modules/cjs/loader.js:768)
at require (internal/modules/cjs/helpers.js:68)
at vendor-bundle.js:7033
at new Promise (<anonymous>)
at createLoader (vendor-bundle.js:7032)
Let me know if I can provide further information.
electron now requires you to add in nodeIntegration: true in order to be able to import electron in your render process
You cannot directly use electron in a renderer process, use electron.remote:
const { remote } = require('electron');
const window = new remote.BrowserWindow({ width: 800, height: 600 });
See https://electronjs.org/docs/api/remote
After Using the chrome debugger for a really long time trying to locate when this error is happening it isn't related to electron in the slightest. The vendor bundle I am using is passing in an incorrect value for one of it's dependencies
Thanks to everyone for your time.
Related
I have an electron app that works fine in development. But when I build to linux-x64, and try to open the executable, the program crashes with the error:
[xxxx:ERROR:sandbox_linux.cc(377)] InitializeSandbox() called with multiple threads in process gpu-process.
According to this page, https://simpleit.rocks/linux/ubuntu/fixing-common-google-chrome-gpu-process-error-message-in-linux/ this is a common problem in chrome-linux, and can be solved with the command:
google-chrome --disable-gpu --disable-software-rasterizer
However, I don't know how/where to implement this inside electron.
In reality, my app is a react project, converted into an electron project by by adding the following file as the entry. This is the only electron related file in my project (meaning it was 100% webapp aside from this).
const electron = require('electron'),
app = electron.app,
BrowserWindow = electron.BrowserWindow;
const path = require('path'),
isDev = require('electron-is-dev');
let mainWindow;
const createWindow = () => {
mainWindow = new BrowserWindow({ width: 480, height: 320 })
const appUrl = isDev ? 'http://localhost:3000' :
`file://${path.join(__dirname, '../build/index.html')}`
mainWindow.loadURL(appUrl)
mainWindow.maximize()
mainWindow.setFullScreen(true)
mainWindow.on('closed', () => mainWindow = null)
}
app.on('ready', createWindow)
app.on('window-all-closed', () => {
// Follow OS convention on whether to quit app when
// all windows are closed.
if (process.platform !== 'darwin') { app.quit() }
})
app.on('activate', () => {
// If the app is still open, but no windows are open,
// create one when the app comes into focus.
if (mainWindow === null) { createWindow() }
})
app.commandLine.appendSwitch("disable-software-rasterizer");
app.commandLine.appendSwitch('disable-gpu');
This should do the trick.
Adding those to the commendLine to your electron app.
This bug that I read helped me:
https://github.com/electron/electron/issues/28164
I am trying to open a dialog box in my electron app but when I Try importing it in my app.js the error in the title shows up even thought 'enableRemoteModule' is set to true .
I am trying to open a dialog box in my electron app but when I Try importing it in my app.js the error in the title shows up even thought 'enableRemoteModule' is set to true .
app.js
const { dialog } = require("electron").remote;
const OpenBookBtn = document.getElementById("OpenBookBtn")
const viewerElement = document.getElementById('viewer')
const CloseBookBtn = document.getElementById("CloseBookBtn")
WebViewer({
path:'../public/lib',
},viewerElement).then(instance =>{
instance.setTheme("dark");
})
viewerElement.style.display = 'none'
OpenBookBtn.addEventListener('click',()=>{
const file = dialog.showOpenDialog();
viewerElement.style.display = "block"
})
CloseBookBtn.addEventListener('click',(event)=>{
viewerElement.style.display = 'none'
})
index.js
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({
webPreferences: {
nodeIntegration: true,
enableRemoteModule: true,
contextIsolation: false,
},
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);
// 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.
First install the remote module using
> npm install #electron/remote
In the new versions of electron, you have to include remote as
const remote = require('#electron/remote');
const { dialog } = remote;
And in your index.js file add the following
const remoteMain = require('#electron/remote/main');
remoteMain.initialize();
Also, after creating the mainWindow object
remoteMain.enable(mainWindow.webContents)
NOTE: Electron 17.0.1
I'm so confuse about to use the win.loadURL function in Electron.
For main purpose, to create a dark theme for chat application.
I want to loadURL in Electron and inject CSS to change to dark theme.
BUT when I use loadURL and then run Electron app.
It will show an error "window.require is not a function"
and "Uncaught TypeError: Cannot read properties of undefined (reading 'instance')"
here is my code:
// main.js
const { app, BrowserWindow } = require("electron");
const path = require("path");
function createWindow() {
const win = new BrowserWindow({
width: 1200,
height: 800,
webPreferences: {
preload: path.join(__dirname, "preload.js"),
},
});
win.webContents.openDevTools();
win.loadURL("https://seatalkweb.com/");
}
app.whenReady().then(() => {
createWindow();
app.on("activate", () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
});
app.on("window-all-closed", () => {
if (process.platform !== "darwin") {
app.quit();
}
});
// preload.js
window.addEventListener("DOMContentLoaded", () => {
const replaceText = (selector, text) => {
const element = document.getElementById(selector);
if (element) element.innerText = text;
};
for (const type of ["chrome", "node", "electron"]) {
replaceText(`${type}-version`, process.versions[type]);
}
});
and this is an error:
I do not know why it has an error only this website when open in electron? (no problem if open in chrome)
this website is https://seatalkweb.com/
and it fine if I use other URL instead (such as google.com, facebook.com, etc.)
How can I fix it ?
and could somebody can explain me about this problem ?
Seems weird like a require is called is your page but it's maybe an Electron call du to the LoadUrl... If it's a require problem you may need to activate the Node integration..
const win = new BrowserWindow({
width: 1200,
height: 800,
webPreferences: {
preload: path.join(__dirname, "preload.js"),
nodeIntegration: true
},
});
If it's not from Electron Node integration, then in may be a problem in your web page script.
I've started building an electron application from scratch. So far I can modify the mainWindow by inserting all the logic in main.js, but I'd like to keep the logic in separate files. Unfortunatly I fail to import them correctly, so help would be nice..
// main.js
const { app, BrowserWindow, Menu, dialog } = require('electron');
const fs = require('fs');
const { test } = require('./test'); // test module to be imported
let win;
function createWindow() {
win = new BrowserWindow({
icon: `file://${__dirname}/dist/text-editor/favicon.ico`,
webPreferences: {
nodeIntegration: true
}
});
win.maximize();
win.loadURL(`file://${__dirname}/dist/text-editor/index.html`);
win.webContents.openDevTools();
//menu bar
const template = getTemplate();
const menu = Menu.buildFromTemplate(template);
Menu.setApplicationMenu(menu);
win.on('closed', function () {
win = null;
});
console.log(test.getName()); // throws error
}
// create window on electron init
app.on('ready', createWindow);
// quit when all windows are closed
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', function () {
if (win === null) {
createWindow();
}
});
function getTemplate() {...} // for example move this method to new file
// test.js
const getName = () => {
return "Tom";
};
module.exports.getName = getName;
Running this code with ng build --prod && electron . throws:
Cannot read property 'getName' of undefined.
Thanks in advance ;)
Please import your js as const test = require('./test') and then use test.getName() in your main js file. when calling const {test} is trying to import the test object in the at relevant file . You can read more about that from this answer
I want to store images on the users computer, so I figure it should be stored in users data folder, as described here.
app.getPath(name)
name. Returns String - A path to a special directory or file associated with name. On failure an Error is thrown. You can request the following paths by the name:
home User's home directory
appData Per-user application data directory, which by default points to:
%APPDATA% on Windows
$XDG_CONFIG_HOME or ~/.config on Linux
~/Library/Application Support on macOS
userData The directory for storing your app's configuration files, which by default it is the appData directory appended with your app's name.
...
This is what I think you're supposed to do:
const app = require('electron');
alert(app.getPath('userData'));
But I get "getPath is not a function". I am not sure where to put it. It does not work from my html file or the renderer file, and I'm not sure how to use it from the main file because that's not linked to the web page.
Since the remote method is being considered deprecated, as shown here, I'd suggest you do this:
const {app} = require('electron');
console.log(app.getPath('userData'));
remote is considered dangerous.
app.getPath will be always available in main process.
Here is how to do it in renderer process without using remote (electron 7+)
Basically you have to use invoke in renderer.
in main
ipcMain.handle('read-user-data', async (event, fileName) => {
const path = electron.app.getPath('userData');
const buf = await fs.promises.readFile(`${path}/${fileName}`));
return buf;
})
in renderer
ipcRenderer.invoke('read-user-data', 'fileName.txt').then(
result => doSomething()
);
Here is what I use when I need to switch between dev and release
const electron = require('electron');
export const userDataPath = (electron.app || electron.remote.app).getPath(
'userData'
);
Another way to prevent the error "getPath is not a function" is to make the code work both in the renderer process and the main process:
const electron = require('electron');
const configDir = (electron.app || electron.remote.app).getPath('userData');
console.log(configDir);
I had trouble with app.getPath('userData') to save/load config files, etc and ended up using OS specific env vars in the meantime:
const getAppBasePath = () => {
//dev
if (process.env.RUN_ENV === 'development') return './'
if (!process.platform || !['win32', 'darwin'].includes(process.platform)) {
console.error(`Unsupported OS: ${process.platform}`)
return './'
}
//prod
if (process.platform === 'darwin') {
console.log('Mac OS detected')
return `/Users/${process.env.USER}/Library/Application\ Support/${YOUR_APP_NAME}/`
} else if (process.platform === 'win32') {
console.log('Windows OS detected')
return `${process.env.LOCALAPPDATA}\\${YOUR_APP_NAME}\\`
}
}
if you wanna do it in renderer process
try this,it is work for me
// main.js
const electron = require('electron')
const electronRemote = process.type === 'browser' ? electron :
require('#electron/remote')
const { app, ipcMain, Menu, globalShortcut } = require('electron')
const BrowserWindow = electronRemote.BrowserWindow
const isDev= require('electron-is-dev')
const { initialize, enable } = require('#electron/remote/main')
initialize()
let mainWindow
app.on('ready', ()=>{
mainWindow = new BrowserWindow({
width: 1024,
height: 600,
minWidth:600,
webPreferences: {
nodeIntegration: true,
enableRemoteModule: true,
contextIsolation: false
}
})
enable(mainWindow.webContents)
})
render process
// render process
const { app } = window.require('#electron/remote')
const savedPath = app.getPath('userData')