Electron build failed to load index.html - electron

I'm trying to build my electron application with electron-builder, I have successfully built front-end which was react and did also pass homepage: "./" in my package.json. I have also used hashbrowser as it was mentioned here
but still when I build my app, I get this message in console with white screen:
Not allowed to load local resource. I have passed webSecurity: false in webPreferences electron, It made error go away but didn't fix the problem and still getting white page.
this is my electron index.ts:
let mainWindow: BrowserWindow;
const createWidnow = () => {
mainWindowFunctions();
mainWindow = new BrowserWindow({
minHeight: 600,
minWidth: 800,
x: appXAndY.x,
y: appXAndY.y,
width: appWidthAndHeight.width,
height: appWidthAndHeight.height,
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
preload: path.join(__dirname, "preload.js"),web
},
autoHideMenuBar: true,
});
mainWindow.loadURL(
isDev ? "http://localhost:3000/" : `file://${__dirname}/../build/index.html`
);
if (isDev) {
mainWindow.webContents.openDevTools();
}
}
app.whenReady().then(async () => {
createWidnow();
app.on("activate", () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWidnow();
}
});
});
app.on("window-all-closed", () => {
if (process.platform !== "darwin") {
db.close();
app.quit();
}
});
const mainWindowFunctions = () => {
const files = glob.sync(
path.join(__dirname, "./controllers/**/*.js").split(path.sep).join("/")
);
files.forEach((file) => {
require(file);
});
};
I tried webSecurity false but didn't help

The problem is with Electron Packager. Just use Electron Builder. Then you can get the installer using wix3.

Related

How to make a splash screen on Electron?

I'm new to Electron and I joined an existing project. I'm trying to add an image before the main screen of the app that will last 5 seconds. At first, I tried it with useState and setTimeone but I've realized I'm in the wrong place of the code.
After reading all kinds of solutions, and running the app - I now need your help.
This is some of the code in my main.ts file:
mainWindow = new BrowserWindow({
show: false,
width: 521,
height: 712,
icon: getAssetPath('icon.png'),
webPreferences: {
nodeIntegration: true,
contextIsolation: true,
preload: app.isPackaged
? path.join(__dirname, 'preload.+212 662-122618 js')
: path.join(__dirname, '../../.erb/dll/preload.js'),
},
});
mainWindow.loadURL(resolveHtmlPath('index.html'));
mainWindow.on('ready-to-show', () => {
if (!mainWindow) {
throw new Error('"mainWindow" is not defined');
}
if (process.env.START_MINIMIZED) {
mainWindow.minimize();
} else {
mainWindow.show();
}
});
mainWindow.on('closed', () => {
mainWindow = null;
});
const menuBuilder = new MenuBuilder(mainWindow);
menuBuilder.buildMenu();
// Open urls in the user's browser
mainWindow.webContents.setWindowOpenHandler((edata) => {
shell.openExternal(edata.url);
return { action: 'deny' };
});
// Remove this if your app does not use auto updates
// eslint-disable-next-line
new AppUpdater();
};
/**
* Add event listeners...
*/
app.on('window-all-closed', () => {
// Respect the OSX convention of having the application in memory even
// after all windows have been closed
if (process.platform !== 'darwin') {
app.quit();
}
});
app
.whenReady()
.then(() => {
createWindow();
app.on('activate', () => {
// 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 (mainWindow === null) createWindow();
});
})
.catch(console.log);

Electron App - How do i open link in browser?

im trying to open a link in a new browser window using a Electron App.
const test = () => {
const shell = window.require('electron').shell;
shell.openExternal("https://google.com");
}
When i do this, i get error "window.require is not a function"
I have ofcourse made my research on this, and found several "fixes" but none has worked for me. I have edited my webpack.config.js to this:
module.exports = {
configureWebpack: {
externals: {
'./cptable': 'var cptable'
},
resolve: {
fallback: {
'fs': false,
'crypto': false,
'path': false,
}
}
},
}
I have also made sure nodeIntegration enabled like so:
const mainWindow = new BrowserWindow({
width: 1280,
height: 720,
webPreferences: {
nodeIntegration: true
},
autoHideMenuBar: true,
resizable: false,
webPreferences: {
preload: path.join(__dirname, 'preload.js')
}
})
```
still no success. any idea?
renderer.js - from your renderer send request.
const response = await window.electronAPI.openLinkPlease()
preload.js - you have this middleware where your request will receive to send to electron.
process.once("loaded", () => {
contextBridge.exposeInMainWorld('electronAPI', {
openLinkPlease: () => ipcRenderer.invoke('openLinkPlease'),
})
});
electron.js - here you will get your request to open and electron will open this url in your default browser.
First add at the very beginning const {shell} = require("electron"); to add shell capabilities and than after
preload: path.join(__dirname, 'preload.js'),
},
});
add
ipcMain.handle('openLinkPlease', () => {
shell.openExternal("https://google.com");
})
This is the screen how it works from my application

require cannot be used in Electron's preloadjs

main.js
//...
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
preload: path.join(__dirname, './preload/preload.js')
}
});
//...
preload.js
const { contextBridge, ipcRenderer } = require('electron');
const qrcode = require('qrcode');
contextBridge.exposeInMainWorld('electronAPI', {
qrc: qrcode
})
the error
Unable to load preload script: F:\project\bluetools\preload\preload.js
Error: module not found: qrcode
Although direct exposure is not a good behavior, but I need to do it; and the example in the official documentation can be exposed directly, although it is not recommended; but why I require any third-party package in preloadjs shows "module not found: xxx"
Just add nodeIntegration: true to webPreferences. Like that.
//...
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true,
preload: path.join(__dirname, './preload/preload.js')
}
});
//...
I refer to here, I have got a solution, but it seems to be more troublesome, but what is this compared to security and normative?
ipc.js
module.exports = {
xxx_req: (argements) => {
const { ipcMain, winb: win } = argements;
ipcMain.on('xxx_req', (event, response) => {
win.webContents.send("xxx", "hello");
});
}
}
main.js
const ipcm = require('./ipc.js');
const createWindow = () => {
const win = new BrowserWindow({...});
ipcm.xxx_req({ ipcMain, winb: win })
}
preload.js
const { contextBridge, ipcRenderer } = require('electron');
contextBridge.exposeInMainWorld('electronAPI', {
xxx_req: (response) => ipcRenderer.send('xxx_req',response),
xxx: (callback) => ipcRenderer.on('xxx',callback),
})
index.js(render process)
window.electronAPI.xxx_req("hello");
window.electronAPI.qrcode((event, detail) => {
console.log(detail)
});
If you still don't understand why I did this, please refer to here.

Electron how to redirect users between various .html files

I am looking to try to redirect users from "home.html" to "dashboard.html". I've searched far and wide, yet I haven't found an answer.
When creating your window with the BrowserWindow module, you would have used the method win.loadFile(filePath[, options]) to load your html file.
Once the logic to change pages is successful, all you need to do is execute the win.loadFile(filePath[, options]) line of code again with the path to your new file.
As win.loadFile(filePath[, options]) returns a promise, let's add a .then() statement as well (though not requried).
main.js (main thread)
const electronApp = require('electron').app;
const electronBrowserWindow = require('electron').BrowserWindow;
const nodePath = require("path");
let window;
function createWindow() {
const window = new electronBrowserWindow({
x: 0,
y: 0,
width: 800,
height: 600,
show: false,
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
preload: nodePath.join(__dirname, 'preload.js')
}
});
window.loadFile('home.html')
.then(() => { window.show(); });
return window;
}
electronApp.on('ready', () => {
window = createWindow();
});
// Run when logic to change to dashboard is successful.
function showDashboard() {
window.loadFile('dashboard.html')
.then(() => { window.show(); })
}

Electron Uncaught ReferenceError: require is not defined | I have nodeIntegration set to true

I am getting this error whilst using the latest version of Electron. I have nodeIntegration set to true in my main javascript file. I have copy and pasted this code from a working Electron application but it doesn't seem to work with my new app.
Electron Version: ^12.0.0
My main JS
//Require Electron
const { BrowserWindow, app, autoUpdater, globalShortcut, ipcMain } = require('electron');
const main = require('electron-reload');
//Electron reload
const electron_reload = require('electron-reload')(__dirname);
//Disable security warnings
process.env['ELECTRON_DISABLE_SECURITY_WARNINGS'] = 'true';
//Main window
function createMain() {
const main = new BrowserWindow({
minWidth: 425,
minHeight: 524,
width: 1600,
height: 900,
frame: null,
icon: './assets/icon.png',
webPreferences: {
nodeIntegration: true,
nodeIntegrationInWorker: true,
nodeIntegrationInSubFrames: true,
enableRemoteModule: true,
}
});
main.loadFile('./HTML/index.html');
main.setMenu(null);
main.webContents.toggleDevTools();
main.webContents.on('did-finish-load', function () {
main.show();
//Ctrl+Shift+I - Open Developer Tools
globalShortcut.register('CommandOrControl+Shift+I', () => {
console.log('Developer Tools Opened');
main.webContents.toggleDevTools();
});
//Make full screen
globalShortcut.register('F11', () => {
main.maximize();
})
});
//Tries to quit the application when main window is closed
main.on('closed', function () {
app.quit();
});
}
//Once the Electron application is initialised (when it is ready) the function createMain is called
app.whenReady()
.then(createMain)
.then(console.log('Launching ChecklistsPro'));
//When the application is launched, if it has no windows open then it will call the createMain function
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createMain();
}
});
Trying to use require
const electron = require('electron');
I have had the same issue.
It comes with the update from electron 11.x to 12.x See here: https://www.electronjs.org/releases/stable#release-notes-for-v1200
You have to disable contextisolation, which changed from beeing true by default in the new electron version.
function createWindow () {
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
})
win.loadFile('index.html')
}
Another solution is to downgrade to electron 11.x where contextIsolation: false is the default.
My sources:
https://www.reddit.com/r/electronjs/comments/lxjva0/required_not_defined_but_nodeintegration_set_to/
Picture of electron Changelog

Resources