Electron.js Uncaught ReferenceError: require is not defined - javascript

I am trying to make a new Electron desktop app.
by the way, when I insert electron module, I get this error.
If you are familiar with electron, can you help me to resolve this error?
I already tried to fix it.
include require.js.
but not working yet.
<script>
const electron = require('electron'); // I get error at this line.
const {ipcRenderer} = electron;
const form = document.querySelector('form');
form.addEventListener('submit', submitForm);
function submitForm(e) {
e.preventDefault();
}
</script>

If you are using Electron 5.0, then nodeIntegration is false by default in BrowserWindows so you need to specify it explicitly when you create your window:
mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true
}
})

You need to install electron
npm install electron --save-dev
--save-dev because electron is an development dependency.

Related

Cannot use module "dotenv" in my preload.js even if I have it in my dependencies

I have just started using Electron.
This is the start of my preload.js:
const { contextBridge } = require('electron');
require('dotenv').config();
// ...
When I used npm start, the app started normally, except that the preload.js didn't do anything. I opened the developer tools and saw this error:
Error: module not found: dotenv
at preloadRequire (...)
...
Then I checked my npm-shrinkwrap.json:
"devDependencies": {
// ...
"dotenv": "^16.0.3",
"electron": "^22.1.0"
}
Well, it sure had dotenv.
So, how can I make preload.js be able to use dotenv?
Thanks to Alexander Leithner, I worked out the problem.
In the documentation, it says the 'sandbox' limits what I can 'require' from preload.js; so to disable it, set sandbox: false or nodeIntegration: true in webPreferences in the BrowserWindow options.
Example
app.whenReady().then(() => {
const win = new BrowserWindow({
webPreferences: {
nodeIntegration: true
}
})
win.loadURL('https://google.com')
})

Failed to load resource (file not found) Electron js cannot import or export

Failed to load resource: net::ERR_FILE_NOT_FOUND
I am using latest version of npm, node.js and electron.
My html file calls upon a terrautils.js:
<script type="module" src="./terrautils.js"></script>
My terrautils.js file has first line as:
import { LCDClient, Coin } from './node_modules/#terra-money/terra.js';
Which is the link to an npm module that I want to use, and I have it installed and have confirmed that the folder is really there using file explorer. I also know the module works perfectly file, because this issue only happens when I run using npm start but when I run using node terrautils.js and swap from using import to using require, it works perfectly fine.
This is something to do with electron I think, and not sure what to do. My main.js has createWindow function like:
function createWindow (site) {
var win = new BrowserWindow({
width: 700,
height: 600,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
nodeIntegration: true,
contextIsolation: true,
devTools: true,
}
})
win.loadFile(site)
}
I do not care about security, I just want this to work. Thank you.
Solution:
Change html invoking of the js file to this instead:
<script>
require('./terrautils.js')
</script>
dont know how it works, but it does.

Uncaught ReferenceError: require not defined (electron)

I am trying to create a quote widget on electron. For renderer process, I created index.js and coded like below
console.log('from renderer');
var request = require('request');
const electron = require('electron');
var url ="https://quotesondesign.com/wp-json/wp/v2/posts/?orderby=rand&_="+rnd;
request(url, function(error, response, body) {
if(error)
{
document.getElementById("quote").innerHTML = 'Unable to fetch the quote plaese check the network connection';
return;
}
let bodyJSON = JSON.parse(body);
console.log(bodyJson);
let randomQuote = bodyJSON[0]["content"]["rendered"];
document.getElementById("quote").innerHTML = randomQuote;
});
And index.html has
<div id="quote">
</div>
<script src="index.js">
// require ('index.js');
</script>
If I use require ('index.js'); in script tag, it doesn't work. So I used src="index.js". Now renderer process works but on console, it shows "Uncaught ReferenceError: require is not defined at index.js:3"
My 1st query is why require ('index.js'); on script tag doesn't work on index.html
and 2nd query is how to fix the Uncaught ReferenceError problem on index.js
My electron version is v8.2.0 and node version is v12.16.1 and dependencies on package.json are as follows:
"dependencies": {
"request": "^2.88.2",
"require": "^2.4.20"
}
Anyone help me please. Thanks in advance.
Since Electron 5, Node integration in the renderer process is disabled by default. To get around that, you need to declare nodeIntegration: true when instantiating your BrowserWindow.
// In the main process.
const { BrowserWindow } = require('electron')
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true
}
})
Edit: As of Electron 12, you'll also need to define contextIsolation: false in order to do this, as the default value of the flag has changed.
https://www.electronjs.org/docs/breaking-changes#default-changed-contextisolation-defaults-to-true
The reason why require ('index.js'); doesn't work in the script tag is because require isn't defined for the browser. It is only defined for Node. The reason why you are getting the ReferenceError in index.js is because what <script src="index.js> is actually doing is running the code in index.js in the browser environment. So since it is being run in the browser require isn't defined here also.

Electron window shows a screenshot of the screen

So I have an electron app named main.js which I start with npm start. I've set the start script in package.json to electron main.js and have also tried electron .. When running npm start, everything starts without any errors but the electron window only shows a snapshot of what was on the screen when I started it. I've tried refreshing it but nothing seems to work. Here is how it looks:
Image
It should view localhost:3001 but it doesn't. I've also tried to run electron . directly in the terminal but that gives me electron: command not found. When running ./node_modules/electron/dist/electron . it starts as it should but the same problem occurs. Here is main.js:
const electron = require('electron');
const app = electron.app;
const BrowserWindow = electron.BrowserWindow;
const core = require('./app');
let mainWindow
function createWindow() {
mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: { webSecurity: false },
nodeIntegration: false,
})
mainWindow.loadURL('http://localhost:3001');
// mainWindow.setFullScreen(true)
// mainWindow.setMenu(null);
mainWindow.webContents.openDevTools()
mainWindow.on('closed', function () {
mainWindow = null
})
console.log('Electron window ready')
}
app.on('ready', createWindow)
app.on('window-all-closed', function () {
app.quit()
})
core.start()
It seems you didn't install Electron globally, for that you need to run npm install -g Electron
Replace mainWindow.loadURL('http://localhost:3001'); With:
mainWindow.loadURL(
url.format({
pathname: path.join(__dirname, "index.html"),
protocol: "file:",
slashes: true
})
);
You have not shared your package.json file, but I will guess you did not run npm install --save electron in your terminal.
Also, instead of:
const electron = require('electron');
const app = electron.app;
const BrowserWindow = electron.BrowserWindow;
you want to write it like so:
const electron = require('electron');
const { app, BrowserWindow } = electron;
I would review ES6 destructuring and unless you did not share the code with us, you should start your electron project by assuring that the app object is ready and loading your file like so:
let mainWindow;
app.on('ready', () => {
mainWindow = new BrowserWindow({});
mainWindow.loadURL(`file://${__dirname}/main.html`);
});
You will notice I declared an empty mainWindow variable to take care of any scoping issues you may have as you may have to use mainWindow in other functions as well.

Electron: Why occurs 'Uncaught ReferenceError: require is no defined.'?

I have a problem problem in my program using Electron.
First, I was typing require() code in 'main.js'.
const { app, BrowserWindow, globalShortcut, Menu, ipcMain } = require('electron')
Above code does not show an error from console. And I have creating another source file func.js.
I was typing require() code in func.js.
const { ipcRenderer, remote } = require('electron')
But above code shows an error in the console.
So I don't know what is wrong. The ES6 script uses the import () statement, but I do not really know if there was an error in main.js, but I do not know why other files fail.
I got the same error & solved by adding the line bellow in main js file:
from:
win = new BrowserWindow({
})
to:
win = new BrowserWindow({
webPreferences: {nodeIntegration: true},
})
This occurs when you introduce a connecting JS code between html and corresponding Javascript file.

Categories