how to solve this error indexhtml :Uncaught ReferenceError: require is not defined in electron [duplicate] - node.js

This question already has answers here:
With contextIsolation = true, is it possible to use ipcRenderer?
(3 answers)
Closed 1 year ago.
> index.html:
As u can see in index.html code (const electron = require('electron');this require arise an error as require is not define i use window10.
<script>
const electron = require('electron');
const { ipcRenderer } = electron;
document.querySelector('form').addEventListener('submit',(event) =>{event.preventDefault();
event.preventDefault();
const file =document.querySelector('input').files[0];
});
</script>
> 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: {
nodeIntegration: true, // is default value after Electron v5
contextIsolation: true, // protect against prototype pollution
enableRemoteModule: false, // turn off remote
preload: path.join(__dirname, "preload.js") // use a preload script
}
});
mainWindow.loadFile('index.html')

Electron is a package you should use in the nodejs environment, not in the browser. Also in the browser you can't use the require function, you should use instead the import and export syntax.
That because javascript is a script language meant to run in browsers, it doesn't make sense to require electron in your frontend script, but, since your serving your files through the electron service and not in a browser window you can access the require by calling the window.require('pckg') method, still doesn't make any sense to require electron in a client-side window tho, it's like if an express server renders a page that creates another server.
If you just want to create another window you should do that in the main electron file, in your case the Main.js file.

Related

Electron Global Shortcut alternative without reserving the key

How can i capture keypress in Electron without globalShortcut and without losing the key functionality. For example i want to capture Tab press but without losing it's ability to indent for example in visual studio code.
I use Electron 13.0 because if i use higher some required modules don't work.
I tried iohook but throws iohook.node module not found. I think it doens't have support for Electron 13 yet.
Anyone ideea how can i do accomplish this? Thank you !
Electron can be a bit of a headache when it comes to communicate between the window and the main process, and for good reason: Security.
However, this problem has two solutions:
Not recommended: plain ipcRenderer required with { nodeIntegration: true } and window.electron in index.html, that can cause a lot of trouble, don't do that, you give access to the user to all nodejs functions, like fs, child_process, ...
Recomended: preload. Preload makes the bridge between the process and the window allowing you to pick what you want to share with the window, in this case, ipcRenderer without the whole electron access.
Read more about Electron secuity here
First, create a preload.js to pass scope isolated ipcRenderer.send function to the window
// preload.js
const { contextBridge, ipcRenderer } = require('electron');
const exposedAPI = {
sendMessage: (message) => {
ipcRenderer.send('my-event', string);
}
};
contextBridge.exposeInMainWorld("electron", exposedAPI);
More about contextBridge here
In the main electron script
// main.js
const { ipcRenderer } = require('electron');
...
const window = new BrowserWindow({
...
preload: 'my/preload/path/preload.js', // Here preload is loaded when the window is created
})
...
ipcRenderer.on('my-event', (string) => {
// do struff with string
});
Great full example here
Finally, the window where you want to capture the event from without changing the behaviour
// index.html or your-script.js
document.addEventListener('keydown', (evt) => { // keyup, keydown or keypress
window.electron.exposedAPI.sendMessage('key was pressed');
});

Electron frameless window not closing

So i'm developing a program using Electron (11.1.1) and the button i'm using to close the program is not working
I've also downloaded this tutorial and tried to run it and it also fails to close. I'm not really sure if this is a problem with my code but here is my close function just in case.
const electron = require('electron')
const path = require('path')
const remote = electron.remote
function closeWindow(){
console.log("CLOSE")
var window = remote.BrowserWindow.getFocusedWindow();
window.close();
}
I know the button works because when I code another function with console.log it seems to print that but when i run the function above it doesn't seen to print anything (Also node intergration is set to true)
Alright so I have fixed the problem.
In Electron 10+ the tag "enableRemoteModule" is set to false by default. So to get the Remote Module to work you need to set it to true in the BrowserWindow WebPreferences. You can do this by adding
webPreferences: {nodeIntergration: true, enableRemoteModule: true}
into your BrowserWindow object!

Nodejs/electron Override chromium browser timeout.

Been looking all over for this information, closest i can see is the
command line switches. i have a web page that i ported to electron and im trying to override the Browser inactivity timeout. for example running a report over 2 minutes the browser times out the connection. My thinking for a quick fix was to wrap in electron and extend the browser timeout.
https://peter.sh/experiments/chromium-command-line-switches/#timeout
https://github.com/electron/electron/blob/master/docs/api/chrome-command-line-switches.md
In Electron the main.js looks to have wrapped the modules in webpack
in all of the examples ive found
it looks like this
You can use app.commandLine.appendSwitch to append them in your app's main script before the ready event of the app module is emitted:
const { app } = require('electron')
app.commandLine.appendSwitch('remote-debugging-port', '8315')
app.commandLine.appendSwitch('host-rules', 'MAP * 127.0.0.1')
app.on('ready', () => {
// Your code here
})
however in my electron file my const app is actually
const path = __webpack_require__(14);
const electron = __webpack_require__(18);
const unusedFilename = __webpack_require__(20);
const pupa = __webpack_require__(23);
const extName = __webpack_require__(24);
const {app, shell} = electron;
i have tried
app.commandLine.appendSwitch("--disable-renderer-backgrounding");
app.commandLine.appendArgument('--disable-timeouts-for-profiling');
Doesnt seem to work, Any hints would be appreciated.

Electron - "Cannot read property 'on' of undefined"; tried reinstalling,

I'm testing an electron app but I'm getting this pernicious error:
"TypeError: Cannot read property 'on' of undefined"
The research I've done pointed to either a botched module install, a syntax issue, or passing in an undefined variable to the app.on, and I suspect the issue may be Electron being pointed to incorrectly (now it's being pointed to the folder ending in electron\dist\electron.exe, which I've heard might not the right location), but I'm unsure.
Despite checking the require command, syntax, rechecking, uninstalling, and reinstalling node, I can't seem to make this darn error go away. What could be causing this?
const electron = require('electron');
const os = require('os');
const fs = require('fs');
const app = electron.app;
const BrowserWindow = electron.BrowserWindow;
var Mousetrap = require('mousetrap');
const path = require('path');
const url = require('url');
const ipc = electron.ipcMain;
let mainWindow;
function createWindow () {
// Create the browser window.
mainWindow = new BrowserWindow({width: 800, height: 600})
// and load the index.html of the app.
mainWindow.loadURL(url.format({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file:',
slashes: true
/* More code in this and sub functions*/
}))
}
})
const preferencesManager = require('./preferencesManager');
/******
Send data to database given constructor created in preferencesManager
******/
// First instantiate the class because we want to turn the class into an object to be able to use.
const store = new Store({ //create a new getting and setting logic
//We'll call our data file 'user-preferences'
configName: 'user-preferences',
defaults: {
//800 x 600 is the default size of our window
windowBounds: { width: 800, height: 600}
}
});
// When our app is ready, we'll create our BrowserWindow
app.on('ready',function(){
//Set up a listener for what I've done in keycapture (in the renderer process)
//???
ipc.on('invokeAction', function(event, args){
/* Do some action */
});
});
You are probably trying to run your application like a node app with:
$ node index.js
The electron file is a binary file, not a JavaScript file, when you require it an run with node there will be no object to call electron.app, so it parses for null and cannot have an property. As in the getting started documento of Electron.JS you must run the application like this:
Change your package.json script session adding start:
{
"scripts": {
"start": "electron ."
}
}
Now run:
$ npm start
The code you posted has an error, witch may be an edition error while coping and pasting but it should loose some parenthesis and curly brackets:
function createWindow () {
// Create the browser window.
mainWindow = new BrowserWindow({width: 800, height: 600})
// and load the index.html of the app.
mainWindow.loadURL(url.format({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file:',
slashes: true
/* More code in this and sub functions*/
}))
}
The application should now run correctly. I tested you exact code, removing the libs I did not have and it loaded with no errors.

How to integrate and run existing ReactJS Application in Electron

For instance, I have an ReactJS application: https://iaya-664f3.firebaseapp.com/
You can see in the HTML source the bundle.js file.
I have tried to run this application as desktop application using Electron, which should launch this web application in chromium window but it is not working.
Following is my main React application file app.js sitting in root directory. However compiled files bundle.js and index.html are in ./public/directory.
./app.js
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, browserHistory } from 'react-router';
import routes from './routes';
import {Provider} from "react-redux";
import { createStore, applyMiddleware } from 'redux';
import ReduxPromise from 'redux-promise';
import rootReducer from './reducers/index';
const store = applyMiddleware(ReduxPromise)(createStore)(rootReducer);
ReactDOM.render( <Provider store={store}>
<Router history={browserHistory} routes={routes} />
</Provider> ,
document.getElementById('react-app'));
./index.js
In this file I'm embedding my application to Electron to run in chromium.
var app = require("./app");
var BrowserWindow = require("browser-window");
// on electron has started up , booted up, everything loaded (Chromium ,goen, live)
app.on("ready", function(){
var mainWindow = new BrowserWindow({
width:800,
height:600
});
mainWindow.loadUrl("file://" + __dirname+ "/public/index.html");
});
But this give some error on import React from 'React' line in my ./app.js.
So I assume that, I should only give ./public/index.html file to load which includes the compiled bundle.js. But I wonder, how that will work as the line app.on("ready", function(){ expect an app.
Moreover I have also tried following way in ./index.js but it gives some other error.
const electron = require('electron');
// Module to control application life.
const app = electron.app;
// Module to create native browser window.
const BrowserWindow = electron.BrowserWindow;
const path = require('path');
const url = require('url');
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow;
function createWindow () {
// Create the browser window.
mainWindow = new BrowserWindow({width: 800, height: 600});
// and load the index.html of the app.
/*mainWindow.loadURL(url.format({
pathname: path.join(__dirname, 'public/index.html'),
protocol: 'file:',
slashes: true
}));*/
mainWindow.loadURL("file://" + __dirname+ "/public/index.html");
// Open the DevTools.
mainWindow.webContents.openDevTools();
// Emitted when the window is closed.
mainWindow.on('closed', function () {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
mainWindow = null;
});
}
app.on('ready', createWindow);
// Quit when all windows are closed.
app.on('window-all-closed', function () {
// On OS X it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', function () {
// 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 (mainWindow === null) {
createWindow();
}
});
Basically the thing is very simple. Electron acts just like a desktop chromium wrapper, that displays your any (any) type of web page inside desktop chromium.
So for example, we want to display http://www.google.com then you simply pass this URL to your loadURL() function.
Here is the working copy of code (asked in the question):
const electron = require('electron');
// Module to control application life.
const app = electron.app;
// Module to create native browser window.
const BrowserWindow = electron.BrowserWindow;
app.on('ready', function(){
var mainWindow = new BrowserWindow({width: 800, height: 600});
mainWindow.loadURL("http://localhost:8080/"); // option1: (loading a local app running on a local server)
//mainWindow.loadURL("https://iaya-664f3.firebaseapp.com"); // option2: (loading external hosted app)
// loading developer tool for debugging
mainWindow.webContents.openDevTools();
});
I hope this will clarify the confusion for many people, who are new to Electron. So the final words are that Electron only loads existing and running web application. It does not compile, does not act as a server. It is just a box in which you can put anything and give it a desktop sort of look e.g. menues, desktop notification, local file system access, etc.

Resources