This question already has answers here:
Electron require() is not defined
(11 answers)
Closed 1 year ago.
I am trying to build an electron Desctop app but when I wanted to use the Filesystem (fs) of nodejs I got the error "Uncaught ReferenceError: require is not defined". When I searched for the problem I found some tipps like "delete "type:" "module" " from your package.json or to use import instead but nothing worked out for me. I can not use any modules in general not just fs but everything in my main.js works just fine.
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,
webPreferences: {
nodeIntegration: true
}
});
As you can see require() works but only there.
It does not work when I want to use it in my index.html to read a file.
const { readFile } = require('fs');
readFile('./foo.txt', (err, source) => {
if (err) {
console.error(err);
} else {
console.log(source);
}
});
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Test</title>
<link rel="stylesheet" href="index.css" />
<script defer src="test.js"></script>
</head>
<body class="content">
</body>
</html>
I am not really an experienced programmer so I hope I don't make an obvious mistake and waste your time and I am looking forward to your help.
function createAddItemWindow() {
// Create a new window
addItemWindown = new BrowserWindow({
width: 300,
height: 200,
title: 'Add Item',
// The lines below solved the issue
webPreferences: {
nodeIntegration: true
}
})}
The solution was proposed here.
Related
This problem is so confusing because i don't know where the issue is.
I used vibrancy in my last project with previous electron versions in same machine and those were work properly but know it does not work, and i don't have any idea what is the problem.
I google it and i did not find any question or github issue.
May be the problem is in electron?!!
Here some information that may needed:
System:
MacOS 11.6 x86_64
Electron Version: 15.0.0
Other Dependencies or DevDependencies: Nothing
This is very simple example, and nothing crazy is going on. very very simple:
// File: index.js
// Process: Main
// Location: Root Directory Of Project
// -----------------------------------
const { app, BrowserWindow } = require('electron');
const { join } = require('path');
const isDarwin = process.platform === 'darwin';
let mainWindow;
app.setName('Electron Sample');
const Ready = () => {
mainWindow = new BrowserWindow({
show: false,
vibrancy: 'content',
visualEffectState: 'followWindow',
title: app.getName(),
backgroundColor: false,
webPreferences: {
contextIsolation: false,
nodeIntegration: true,
nativeWindowOpen: false
}
});
mainWindow.loadFile(join(__dirname, './index.html'));
mainWindow
.once('ready-to-show', () => mainWindow.show())
.once('close', () => (mainWindow = null));
};
app.whenReady().then(Ready);
app.on('window-all-closed', () => {
if (!isDarwin) app.quit();
});
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) Ready();
});
<!--
File: index.html
Process: Renderer
Location: Root Directory Of Project
-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<style>
html,
body {
background-color: transparent;
width: 100vw;
height: 100vh;
}
</style>
</head>
<body>
<h1>I Confused! 😭</h1>
</body>
</html>
Project Structure:
node_modules
index.js
index.html
yarn.lock
package.json
This is all information.
The problem is in BrowserWindow Options
This is the correct form of options to enable under-window vibrancy on macOS:
new BrowserWindow({
// Other Options...
transparency: true,
backgroundColor: "#00000000" // transparent hexadecimal or anything with transparency,
vibrancy: "under-window", // in my case...
visualEffectState: "followWindow"
})
more info: Electron BrowserWindow Options
I am a complete beginner to JavaScript and Electron just so you know.
I think I've looked most places, and I haven't found a thing.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>??</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="main">
<button id="get-data" type="submit">Get Data</button>
</div>
<script src="script.js"></script>
</body>
</html>
main.js
const { app, BrowserWindow } = require("electron");
const ipc = require("electron").ipcMain;
app.whenReady().then(() => {
const window = new BrowserWindow({
"center": true,
"width": 500,
"height": 800,
"webPreferences": {
"nodeIntegration": true
}
});
window.loadFile("index.html");
});
ipc.on("uhhm", event => {
event.sender.send("ok", "Hello World!");
});
script.js
const ipc = require("electron").ipcRenderer;
const getDataBtn = document.getElementById("get-data");
getDataBtn.addEventListener("click", () => {
ipc.send("uhhm");
ipc.once("ok", data => {
getDataBtn.innerHTML = "Moving On... " + data;
});
});
I get this error:
Uncaught ReferenceError: require is not defined
at script.js:1
IDK what to do
Have any suggestions?
if you are using a >= 5 version of Electron, you need to enable the nodeIntegration and contextIsolation parameters as follows:
app.on('ready', () => {
mainWindow = new BrowserWindow({
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
}
});
});
I had that issue when I worked for a while with Electron Framework, where I need IPC communication between a renderer process and the main process. The renderer process sits in an HTML file between script tags and generates the same error.
const {ipcRenderer} = require('electron')
//throws the Uncaught ReferenceError: require is not defined
In your case :
const ipc = require("electron").ipcRenderer;
You must to work around that by specifying Node.js integration as true when the browser window (where this HTML file is embedded) was originally created in the main process.
function createWindow() {
// Create a new window
const window = new BrowserWindow({
width: 300,
height: 200,
// The lines below solved the issue
webPreferences: {
nodeIntegration: true
}
})}
That solved the issue for me. The solution was proposed here.
Unable to use any electron or node related operations in electron .
Getting error process not defined.
I Checked at various places they guide to add node Support but that is already Done so stucked here
My Main Application code is
const electron = require("electron");
const { app, BrowserWindow } = electron;
function createWindow() {
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: { nodeIntegration: true },
});
win.loadFile("index.html");
}
app.whenReady().then(createWindow);
app.on("window-all-closed", () => {
if (process.platform !== "darwin") {
app.quit();
}
});
app.on("activate", () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
And Index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Hello World!</title>
</head>
<body style="background: white">
<h1>Hello World!</h1>
<p>
We are using node
<script>
document.write(process.versions.node);
</script>
, Chrome
<script>
document.write(process.versions.chrome);
</script>
, and Electron
<script>
document.write(process.versions.electron);
</script>
.
</p>
</body>
</html>
Update: the answer below is a workaround. You should not disable contextIsolation and you should not enable nodeIntegration. Instead you should use a preload script and the contextBridge API.
In Electron 12, contextIsolation is now by default true
If you set it to false, you will have access to Node.js APIs in the renderer process
function createWindow() {
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
contextIsolation: false,
nodeIntegration: true
},
});
win.loadFile("index.html");
}
⚠️ It's important to note that this is not recommended!
There's a good reason why Electron maintainers changed the default value. See this discussion
Without contextIsolation any code running in a renderer process can quite easily reach into Electron internals or your preload script and perform privileged actions that you don't want arbitrary websites to be doing.
There is no reason to elevate the privileges of your renderer. Any third-party scripts on that page would run with the same privileges and that's definitely not what you want.
Instead you should use a preload script which has that privilege (i.e. can use Node.js APIs by default) but keep contextIsolation=true (which is the default value anyway). If you need to share data between your preload script and your renderer script use contextBridge.
In my example I have exposed data from the preload script to the renderer script under a rather silly namespace (window.BURRITO) to make it obvious that you're in charge:
main.js
const {app, BrowserWindow} = require('electron'); //<- v13.1.7
const path = require('path');
app.whenReady().then(() => {
const preload = path.join(__dirname, 'preload.js');
const mainWindow = new BrowserWindow({ webPreferences: { preload }});
mainWindow.loadFile('index.html');
});
preload.js
const {contextBridge} = require('electron');
contextBridge.exposeInMainWorld('BURRITO', {
getNodeVer: () => process.versions.node,
getChromeVer: () => process.versions.chrome,
getElectronVer: () => process.versions.electron
});
renderer.js
const onClick = (sel, fn) => document.querySelector(sel).addEventListener('click', fn);
onClick('#btn1', () => alert(BURRITO.getNodeVer()));
onClick('#btn2', () => alert(BURRITO.getChromeVer()));
onClick('#btn3', () => alert(BURRITO.getElectronVer()));
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<button id="btn1">Node?</button>
<button id="btn2">Chrome?</button>
<button id="btn3">Electron?</button>
<script src="./renderer.js"></script>
</body>
</html>
I'm new to Electron and working on creating a basic app, the app itself works great while in dev mode, however once I package the app for windows none of the buttons work correctly. I have tried using the browserify but with no luck. I have also messed around with the nodeIntergration set to true and false but that didn't seem to fix my issue either. I understand that require() module is node a server side thing and that the browser cannot natively support it. Any suggestions would be greatly appreciated! Also if you require any additional information or code please let me know.
The error I'm getting is: "Uncaught ReferenceError: require is not defined at index.html:17"
Main JS
const electron = require('electron');
var app = require('electron').app;
var BrowserWindow = require('electron').BrowserWindow;
var mainWindow = null;
app.on('window-all-closed', function() {
if (process.platform != 'darwin')
app.quit();
});
app.on('ready', function() {
mainWindow = new BrowserWindow({webPrefrences: {nodeIntergration: true, enableRemoteModule: true},
width: 600, height: 410, frame: true, transparent: true, resizable: false, icon:
'C:/Users/cody/Projects/QuickLaunch/app/assets/icons/win' + '/icon.ico'});
mainWindow.loadURL('file://' + __dirname + '/index.html');
mainWindow.on('closed', function() {
mainWindow = null;
});
});
index.html
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="default.css"/>
<title>Quick Launch</title>
<link href="https://fonts.googleapis.com/css2?family=Oswald:wght#700&display=swap" rel="stylesheet">
<body style="-webkit-user-select: none;">
<div id="title-bar">
<div id="title-bar-btns">
<script>
(function () {
const remote = require('electron').remote;
function init() {
document.getElementById("min-btn").addEventListener("click", function (e) {
const window = remote.getCurrentWindow();
window.minimize();
});
document.getElementById("close-btn").addEventListener("click", function (e) {
const window = remote.getCurrentWindow();
window.close();
});
};
document.onreadystatechange = function () {
if (document.readyState == "complete") {
init();
}
};
})();
</script>
<button id="min-btn">-</button>
<button id="close-btn">x</button>
</div>
</div>
I am having trouble with my Electron app. I had it working about 9 months ago, but now the custom minimise and maximise buttons I made are not functioning properly.
Here is my file structure
node_modules
...
web
css
main.css
html
index.html
images
...
js
index.js
themes
...
main.js
package.json
package-lock.json
require.js
And here is the contents of index.html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="../css/main.css">
<style type="text/css">* {visibility: hidden;}</style>
<link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,600,700" rel="stylesheet">
<link rel="icon" href="../images/favicon-32x32.png" />
</head>
<body>
<div id="wrapper">
<div id="title-bar">
<div id="title-bar-btns">
<button id="min-btn" onclick="window_minimise()">—</button>
<button id="close-btn" onclick="window_close()">✕</button>
</div>
</div>
...
</div>
<script>
// You can also require other files to run in this process
require('../../renderer.js')
</script>
<script src="../js/index.js" type="text/javascript"></script>
</body>
</html>
And index.js
...
const {BrowserWindow} = require('electron').remote;
function window_minimise(){
let window = BrowserWindow.getCurrentWindow();
window.minimize();
}
function window_close(){
let window = BrowserWindow.getCurrentWindow();
window.close();
}
...
And here is my main.js file
const {app, BrowserWindow} = require('electron')
let mainWindow
function createWindow () {
let mainWindow = new BrowserWindow({
width: 1200,
height: 748,
icon:'web/images/favicon-32x32.png',
resizable: false,
frame: false,
show: false,
backgroundColor: '#171717',
webPreferences: {
nodeIntegration: true
}
})
mainWindow.once('ready-to-show', () => {
mainWindow.show()
})
mainWindow.setMenu(null);
mainWindow.loadURL('http://localhost:8000/html/index.html')
mainWindow.on('closed', function () {
mainWindow = null
})
}
app.on('ready', createWindow)
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') app.quit()
})
app.on('activate', function () {
if (mainWindow === null) createWindow()
})
When I click minimise or maximise, nothing happens. So I went to http://localhost:8000/html/index.html and checked the console, and I saw these errors
Uncaught ReferenceError: require is not defined at index.html:137
Uncaught ReferenceError: require is not defined at index.js:110
I am using electron version 5.0.2 by the way.
If someone could help me resolve this, that would be wonderful.
Thanks.
EDIT: The errors I mentioned above are shown when the page loads, and this error is shown when I click minimise
Uncaught ReferenceError: Cannot access 'BrowserWindow' before
initialization at window_minimise (index.js:113) at
HTMLButtonElement.onclick (index.html:18)
EDIT2: I think the issue is that eel (the code that allows me to interface python with my electron app) requires the webpage to be run on localhost, and thus node features such as require do not work. I go into a bit more detail in a GitHub issue here: github.com/ChrisKnott/Eel/issues/147
All you need to do is add contextIsolation: false after nodeIntegration: true in the webPreferences object
Change your index.js file as follows. Then use nodeRequire instead of require keyword.
initNodeRequire();
const {BrowserWindow} = nodeRequire('electron').remote;
function window_minimise(){
let window = BrowserWindow.getCurrentWindow();
window.minimize();
}
function window_close(){
let window = BrowserWindow.getCurrentWindow();
window.close();
}
function initNodeRequire(){
window.nodeRequire = require;
delete window.require;
delete window.exports;
delete window.module;
}