I build an app with Electron an i try to use a webview to display a file loaded from my disk and i need nodeintegration in the webview. Although it is documented in the Electron Documentation here i can`t get it working.
I created a test project with the main.js file, which creates a BrowserWindow, where i load my index.html and index.js files. The index.js file creates a webview with my file loaded and the file is webview.html with webview.js. I call require in webview.js and i can see in the DevTools, that it is giving the error
Uncaught ReferenceError: require is not defined
at webview.js:2
Here are my testfiles, what am i missing or got this feature removed?
I am using Electron ^12.0.2
main.js
const { app, BrowserWindow, BrowserView } = require('electron')
function createWindow () {
let win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
webviewTag: true,
nodeIntegrationInWorker: true,
nodeIntegrationInSubFrames: true
}
})
win.loadFile('index.html')
return win;
}
app.whenReady().then(() => {
let win = 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>
<div class="root">
</div>
<script src="index.js" charset="utf-8"></script>
</body>
</html>
index.js
function createWebview(id, url) {
//creates a webview with the id of the tab and the url loaded
let webview = document.createElement("webview");
webview.setAttribute("id", id);
webview.setAttribute("src", url);
webview.setAttribute("nodeintegration", "");
webview.setAttribute("preload", "./pre.js")
webview.addEventListener('dom-ready', () => {
webview.openDevTools();
});
console.log(webview);
return webview;
}
document.querySelector(".root").appendChild(createWebview("web", `file://${__dirname}/webview.html`));
webview.html
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
test
<script src="webview.js" charset="utf-8"></script>
</body>
</html>
webview.js
console.log("test");
//a require to test the functionality
const { app, BrowserWindow, ipcMain, Menu, MenuItem } = require('electron');
Edit 1: The preload script is empty.
After thinking much more i came to the solution, that if the webview is similar to the BrowserWindow, then i need to disable contextIsolation in the webPreferences object of the webview. This is definitely something that needs to be added to electron documenten.
I change my index.js file like this
function createWebview(id, url) {
//creates a webview with the id of the tab and the url loaded
let webview = document.createElement("webview");
webview.setAttribute("id", id);
webview.setAttribute("src", url);
webview.setAttribute("nodeintegration", "");
webview.setAttribute("webpreferences", "contextIsolation=false");
webview.addEventListener('dom-ready', () => {
webview.openDevTools();
});
console.log(webview);
return webview;
}
document.querySelector(".root").appendChild(createWebview("web", `file://${__dirname}/webview.html`));
Just add below two attributes in webPreference object to enable nodeIntegration in all js file which contains webView
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
nativeWindowOpen: true,
enableRemoteModule: true,
sandbox:false,
nodeIntegrationInSubFrames:true, //for subContent nodeIntegration Enable
webviewTag:true //for webView
}
don't use webview is not good idea to show external content using webView
it affects performance.!
See docs about webView below
Related
I've been trying to get a preload script to run on my Electron app but it appears to either not be running at all or just not working properly.
I currently have a main file, a preload file, a render file, and a html. I'm just trying to do the stuff from the Electron tutorial on using preload files, so right now my code is something like this:
// main.js
const {app, BrowserWindow, ipcMain, Menu} = require('electron');
const url = require('url');
const path = require('path');
let mainWindow;
const createWindow = () => {
// Create a window
mainWindow = new BrowserWindow({
show: false,
autoHideMenuBar: true,
webPreferences: ({
preload: path.join(__dirname, 'scripts', 'preload.js'),
nodeIntegration: true,
}),
});
mainWindow.maximize();
mainWindow.show();
// Load HTML into window
mainWindow.loadFile('index.html');
// Open Dev Tools
// mainWindow.webContents.openDevTools();
console.log(versions);
}
// preload.js
const {contextBridge} = require('electron');
contextBridge.exposeInMainWorld('versions', {
node: () => process.version.node,
chrome: () => process.version.chrome,
electron: () => process.version.electron,
});
Index.html:
<html lang="en">
<head>
<meta charset="UTF-8">
<meta
http-equiv="Content-Security-Policy"
content="default-src 'self'; script-src 'self'"
/>
<meta
http-equiv="X-Content-Security-Policy"
content="default-src 'self'; script-src 'self'"
/>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="./css/style.css">
<title>Test</title>
</head>
<body>
<h1>Test</h1>
<p id="info"></p>
<script>window.$ = window.jQuery = require('jquery');</script>
<script src="render.js"></script>
</body>
// render.js
const information = document.getElementById('info');
information.innerText = `This app is using Chrome (v${versions.chrome()}),
Node.js (v${versions.node()}), and Electron (v
${versions.electron()})`
Currently my output on the HTML from render.js is "This app is using Chrome (vundefined),Node.js (vundefined), and Electron (vundefined)" and my console.log line in main.js throws up a ReferenceError stating "versions is not defined". Anybody able to shine some light on how I could fix this? Thanks in advance.
I think you made a typo:
In your preload script
contextBridge.exposeInMainWorld('versions', {
node: () => process.version.node,
chrome: () => process.version.chrome,
electron: () => process.version.electron,
});
Should be (add a "s" to process.version
contextBridge.exposeInMainWorld('versions', {
node: () => **process.versions.node,
chrome: () => **process.versions.chrome,
electron: () => **process.versions.electron,
});
Can have a look to the docs:
https://www.electronjs.org/docs/latest/api/process
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.
I'm learning electron, took electron-quick-start and made certain modifications to index.html, main.js and renderer.js following the tutorial at
https://blog.logrocket.com/handling-interprocess-communications-in-electron-applications-like-a-pro/
index.html
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<title>Electron-Process-Comm</title>
<link rel="stylesheet" href="style.css">
<meta charset="UTF-8">
<!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP -->
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'">
<meta http-equiv="X-Content-Security-Policy" content="default-src 'self'; script-src 'self'">
</head>
<body>
<h2 id="mainWindowTitle">I am the main window</h2>
<button id="sendSyncMsgBtn">Ping Main Process</button>
<p id="syncReply">Chilling for response</p>
<!-- You can also require other files to run in this process -->
<script src="./renderer.js"></script>
</body>
</html>
main.js
// Modules to control application life and create native browser window
const {app, BrowserWindow} = require('electron')
const path = require('path')
const ipcMain = require('electron').ipcMain
console.log('Hello')
ipcMain.on('sync-message', (event, arg) => {
console.log('IPCMain')
event.returnValue = 'Message Recieved!'
})
function createWindow () {
// Create the browser window.
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
preload: path.join(__dirname, 'preload.js')
}
})
// and load the index.html of the app.
mainWindow.loadFile('index.html')
}
app.whenReady().then(() => {
createWindow()
app.on('activate', function () {
if (BrowserWindow.getAllWindows().length === 0) createWindow()
})
})
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') app.quit()
})
renderer.js
const electron = require('electron')
const ipc = electron.ipcRenderer
const syncMsgBtn = document.querySelector('#sendSyncMsgBtn')
console.log('Hello renderer')
syncMsgBtn.addEventListener('click', () => {
console.log('Renderer')
const reply = ipc.sendSync('sync-message', 'Sent from main Window')
const message = `Synchronous message reply: ${reply}`
document.querySelector('#syncReply').innerHTML = message
})
const asyncMsgBtn = document.querySelector('#sendAsyncMsgBtn')
asyncMsgBtn.addEventListener('click', () => {
ipc.send('async-message', 'Async message baby')
})
Now, though renderer.js is included in the index.html it is never invoked. The console log doesn't appear and the button click doesn;t respond. Can somebody tell me what i'm doing wrong ?
The code looks fine and should be executed when running. You might be looking at the wrong console? The log statements should appear in the console of the renderer window. To open the Developer Tools, you can press Cmd + Opt + I (macOS) and Ctrl + Shift + I (Windows).
You can find more information about debugging Electron applications in their documentation and the Developer Tools in Chrome's documentation.
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>