Electron require is not defined in renderer process - javascript

I'm starting with electron and for some unknown reason I can't use require() function in renderer process.
Uncaught ReferenceError: require is not defined at index.js:1
package.json
{
"name": "my-electron-app",
"version": "0.1.0",
"author": "your name",
"description": "My Electron app",
"main": "main.js",
"scripts": {
"start": "electron ."
},
"keywords": [],
"license": "ISC",
"devDependencies": {
"electron": "^12.0.2"
}
}
main.js
const { app, BrowserWindow, ipcMain } = require('electron')
const path = require('path')
const ipc = ipcMain;
function createWindow () {
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntergration: true,
contextIsolation: false,
devTools: true,
preload: path.join(__dirname, 'preload.js')
}
})
win.loadFile('index.html')
win.webContents.openDevTools()
ipc.on("closeApp", ()=>{
console.log("clicked on Close btn")
win.close();
})
}
app.whenReady().then(() => {
createWindow()
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow()
}
})
})
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
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.js <span id="node-version"></span>,
Chromium <span id="chrome-version"></span>,
and Electron <span id="electron-version"></span>.
</p>
<button id="closeBtn">close</button>
<script defer src="index.js"></script>
</body>
</html>
index.js
const { ipcRenderer } = require('electron');
const ipc = ipcRenderer;
var closeBtn = document.getElementById('closeBtn');
closeBtn.addEventListener("click", ()=>{
ipc.send("closeApp");
});
Screenshot of my program
I am doing everything like in the tutorial, I have searched for solution for two days and tried everything, nothing works. I am worried that only I have that problem :v

There's a typo in nodeIntegration (you spelled it nodeIntergration). That's probably the problem

Related

electron tabs did not execute the renderer

i started to work with electron tabs and i can show the sites, that i wanted. Now i wanted to show my own little html site in the app.
The HTML site has a button and when you click it, there should be a message in the console. But the .js data (renderer) will not be executed. When i just load the site without the tabview, everything works. I found out, that electron don't load the js script in the DOM. But i dont know a solution for this problem. Here the code for the examples:
this worked
main.js
// Modules to control application life and create native browser window
const {app, BrowserWindow} = require('electron')
const path = require('path')
function createWindow () {
// Create the browser window.
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
webviewTag: true,
nodeIntegration: true,
contextIsolation: false
}
})
// and load the index.html of the app.
mainWindow.loadFile('page.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.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.
html site
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button id="Hello">Say hello</button>
<p id="text">Guten Tag</p>
<script src="renderer.js"></script>
</body>
</html>
renderer.js
const {dialog} = require ('electron');
const button = document.getElementById("Hello");
console.log (button);
function hello () {
const label = document.getElementById("text");
console.log(label.innerHTML);
label.innerHTML = "Hello";
console.log("hello");
}
if (button) {
button.addEventListener('click',hello);
}
package.json
{
"name": "electron-quick-start",
"version": "1.0.0",
"description": "A minimal Electron application",
"main": "main.js",
"scripts": {
"start": "electron ."
},
"repository": "https://github.com/electron/electron-quick-start",
"keywords": [
"Electron",
"quick",
"start",
"tutorial",
"demo"
],
"author": "GitHub",
"license": "CC0-1.0",
"devDependencies": {
"electron": "^21.2.0"
},
"dependencies": {
"electron-tabs": "^1.0.1"
}
}
2nd exapmle (didnt work):
is the same code but in the main you load the page.html and the you need the tab.js.
page.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button id="Hello">Say hello</button>
<p id="text">Guten Tag</p>
<script src="renderer.js"></script>
</body>
</html>
Tabs.js
tabGroup = document.querySelector("tab-group");
tabGroup.on("ready", () => console.info("TabGroup is ready"));
tabGroup.setDefaultTab({
title: "Wikipedia",
src: "https://www.wikipedia.org/",
active: true,
ready: () => console.info("New Tab is ready")
});
tabGroup.addTab({
title: "electron-tabs on NPM",
src: "https://www.npmjs.com/package/electron-tabs",
badge: {
text: "5",
classname: "my-badge"
}
});
tabGroup.addTab({
title: "electron-tabs on Github",
src: "https://www.youtube.com/",
active: true
});
tabGroup.addTab({
title: "My Custom Tab",
src: "page.html",
ready: function(tab) {
tab.element.classList.add("my-custom-tab");
}
});

Electron App Exit immediately after printing command

i'm trying to create a desktop app that can do printing after i clicked some button.
so here is my code.
main.js
const {app,BrowserWindow} = require('electron');
function createWindow(){
const win = new BrowserWindow({
resizable:false
})
win.maximize()
win.removeMenu()
win.loadFile("./index.html")
win.webContents.on('did-create-window',(window,detail)=>{
window.removeMenu()
window.resizable = false
window.webContents.print({silent:false})
})
}
app.whenReady().then(() => {
createWindow()
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow()
}
})
})
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
Index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
whatever
<button onclick="newPrint()">BIGGIE</button>
</body>
<script>
function newPrint(){
var myWindow = window.open("", "MsgWindow", "width=200,height=100");
myWindow.document.write("<p>This is 'MsgWindow'. I am 200px wide and 100px tall!</p>");
}
</script>
</html>
package.json
{
"name": "electron-print",
"version": "1.0.0",
"description": "",
"main": "main.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"electron": "^19.0.2"
}
}
So after i clicked the button, the electron app just suddenly close ! i just don't know why it happened.
and i tried re-creating this app on other computer (Mine was running Win 11 and i thought maybe that was the problem) and it worked just fine !
Could it be that Electron is not fully compatible with Win 11 yet ?
This seems very much like this Electron bug, which is fixed in Electron 19.0.2 which you're apparently on.
Can you reinstall your node modules to confirm that you still see the issue in 19.0.2? This issue would have been present in Electron 19.0.1.

React/JS Uncaught ReferenceError: require is not defined

I have just started learning JS/react and I got an error from a html file complaining as "Uncaught ReferenceError: require is not defined". Please see below as an example.
The error is coming from the line 8
const electron = require('electron');
from the following code
this is addWindow.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Add shopping list item</title>
</head>
<body>
<script>
const electron = require('electron');
const {ipcRenderer} = electron;
const form = document.querySelector('form');
form.addEventListener('submit', submitForm);
function submitForm(){
e.preventDefault();
}
</script>
<form>
<div>
<label>Enter Item</label>
<input type="text" id="item" autofocus>
</div>
<button type="submit">add item</button>
</form>
</body>
</html>
I have researched and noticed a lot of other people are having the issue so I added
nodeIntegration: true,
this is main.js
const electron = require("electron");
const url = require("url");
const path = require("path");
const { app, BrowserWindow, Menu } = electron;
let mainWindow;
let addWindow;
//listen
app.on("ready", function () {
//create new window
mainWindow = new BrowserWindow({
webPreferences: {
nodeIntegration: true,
preload: `${__dirname}/preload.js`,
},
});
//
mainWindow.loadURL(
url.format({
pathname: path.join(__dirname, "mainWindow.html"),
protocol: "file:",
slashes: true,
})
);
//Quit app when closed
mainWindow.on("closed", function () {
app.quit();
});
//build menu from template
const mainMenu = Menu.buildFromTemplate(mainMenuTemplate);
//insert menu
Menu.setApplicationMenu(mainMenu);
});
//handle add window
function createAddWindow() {
//create new window
addWindow = new BrowserWindow({
width: 300,
height: 200,
title: "Add shopping list item",
webPreferences: {
nodeIntegration: true,
preload: `${__dirname}/preload.js`,
},
});
//
addWindow.loadURL(
url.format({
pathname: path.join(__dirname, "addWindow.html"),
protocol: "file:",
slashes: true,
})
);
//garbage collection
addWindow.on("close", function () {
addWindow = null;
});
}
//add clear quit
//create menu template
const mainMenuTemplate = [
{
label: "la",
},
{
label: "File",
submenu: [
{
label: "Add Item",
accelerator: process.platform == "darwin" ? "Command+A" : "Ctrl+A", //mac for darwin
click() {
createAddWindow();
},
},
{
label: "Clear Item",
},
{
label: "Quit",
accelerator: process.platform == "darwin" ? "Command+Q" : "Ctrl+Q", //mac for darwin
click() {
app.quit(); //control Q
},
},
],
},
];
if (process.platform == "darwin") {
// mainMenuTemplate.unshift({});
}
// add dev tool item if not in prod
if (process.env.NODE_ENV !== "production") {
mainMenuTemplate.push({
label: "Developer Tools",
submenu: [
{
label: "Toggle DevTools",
accelerator: process.platform == "darwin" ? "Command+I" : "Ctrl+I",
click(item, focusedWindow) {
focusedWindow.toggleDevTools();
},
},
{
role: "reload",
},
],
});
}
But I still have no luck. Could you please help me?
Thank you.
Have you tried this solution ? :
const ipcRenderer = window.require("electron").ipcRenderer;
Original link : https://github.com/electron/electron/issues/7300#issuecomment-671846484
I think your code need to trans-compile first, this is the scripts part of package.json for my node.js project, maybe useful for you:
"scripts": {
"build": "rm -rf dist && babel ./ -d dist --ignore 'node_modules'",
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon --exec babel-node src/index.js",
"serve": "node ./dist/index.js"
}

Why will my electron.js app not open when I try npm start even though my code is right?

I need help with my simple hello world program based for electron.js.
I was reading the quick guide documentation on the official electronjs.org website.
Esentially I did everything it told me to do on that page including the package.json, package-lock.json, index.html and main.js; and installing electron.js however when I tried to boot up my program in cmd using npm start, I just got 2 messages instead of the program opening.
From there it shows me the cmd command line again waiting for an input which is shown in the picture
I don't know what's wrong and no matter how much I try to edit the package.json and the main.js it still seems to spit out the same error. I was getting so desperate that I just copy and pasted the exact same code in the docs and just edited the author and description as asked in the quick guide.
I am well and truly stuck if anyone has any ideas on how to fix this please let me know, I've also tried some simple troubleshooting, the simple reinstall of the electronjs API, tried administrator cmd, read the forums etc and I can't find anything code will be below..
main.js
const { app, BrowserWindow } = require('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()
}
});
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello World!</title>
<meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />
</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>
package.json
{
"name": "my-first-electron",
"version": "1.0.0",
"description": "",
"main": "main.js",
"dependencies": {
"aws-sdk": "^2.814.0",
"electron": "^11.1.0",
"electron.js": "^0.0.1"
},
"devDependencies": {},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "electron ."
},
"keywords": [],
"author": "",
"license": "ISC"
}

Electron - running into some issues with start command and window sizing

So I've built a trivial application using Electron.
I can start the app using the command 'electron index.html, but not the command 'electron .', even though this is explicitly declared in the package.json
{
"name": "remind-me",
"version": "1.0.0",
"description": "information management tool",
"main": "index.js",
"scripts": {
"start": "electron ."
},
"repository": {
"type": "git",
"url": "tokumk"
},
"dependencies": {
"electron": "^1.6.11"
}
}
a second issue related to window sizing. my BrowserWindow is always the same size regardless of setting it to something else. Here is an example of my index.js. The setting background color is also completely ignored.
index.html
<html>
<head>
</head>
<body>
<div id="container">
<h3>remind me</h3>
<form>
<input type = text action="post"></input>
<input type="submit" value="send" name="submit">
<form>
</div>
</body>
<script>
require('./renderer.js');
</script>
</html>
index.js
const {app, BrowserWindow} = require('electron');
const path = require('path');
const url = ('url');
// window object
let win;
function createWindow(){
// set window size and background color
win = new BrowserWindow({
width: 450,
height: 400,
backgroundColor: '#2e2c29'
});
win.loadURL(url.format({
pathname: path.join(__dir, 'index.html'),
protocol: 'file',
slashes: true
}));
win.webContents.openDevTools();
win.on('closed', ()=> {
win = null;
});
app.on('ready', createWindow);
app.on('window-all-closed', ()=>{
if(process.platform !== 'darwin'){
app.quit();
}
});
}
I think the problem is that you're running the application like electron index.html which just loads index.html in a window and nothing else so if you run electron like: electron index.js I think it would work

Categories