Why Electron Vibrancy Effect Not Working At All - javascript

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

Related

Can't import modules in node.js [duplicate]

This question already has answers here:
Electron require() is not defined
(11 answers)
Closed 1 year ago.
I am trying to build an electron Desctop app but when I wanted to use the Filesystem (fs) of nodejs I got the error "Uncaught ReferenceError: require is not defined". When I searched for the problem I found some tipps like "delete "type:" "module" " from your package.json or to use import instead but nothing worked out for me. I can not use any modules in general not just fs but everything in my main.js works just fine.
const { app, BrowserWindow } = require('electron');
const path = require('path');
// Handle creating/removing shortcuts on Windows when installing/uninstalling.
if (require('electron-squirrel-startup')) { // eslint-disable-line global-require
app.quit();
}
const createWindow = () => {
// Create the browser window.
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true
}
});
As you can see require() works but only there.
It does not work when I want to use it in my index.html to read a file.
const { readFile } = require('fs');
readFile('./foo.txt', (err, source) => {
if (err) {
console.error(err);
} else {
console.log(source);
}
});
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Test</title>
<link rel="stylesheet" href="index.css" />
<script defer src="test.js"></script>
</head>
<body class="content">
</body>
</html>
I am not really an experienced programmer so I hope I don't make an obvious mistake and waste your time and I am looking forward to your help.
function createAddItemWindow() {
// Create a new window
addItemWindown = new BrowserWindow({
width: 300,
height: 200,
title: 'Add Item',
// The lines below solved the issue
webPreferences: {
nodeIntegration: true
}
})}
The solution was proposed here.

How can I send data from my main.js to my index.html (Electron)

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.

How to enable nodeintegration in electron webview?

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

Unable to use Node.js APIs in renderer process

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>

Use Electron remote from other file

I have a file that contains a function that opens a file open dialog. I want to call that function from the app's menu. But when I use require to use the function from the file I get an error.
Code:
Main.js:
const { app, BrowserWindow, Menu } = require('electron');
const url = require('url');
const path = require('path');
const { openFile } = require('./index.js');
let win;
function createWindow() {
win = new BrowserWindow({
width: 800,
height: 600,
icon: __dirname + 'src/styles/media/icon.ico',
webPreferences: {
nodeIntegration: true,
enableRemoteModule: true,
},
});
win.loadURL(
url.format({
pathname: path.join(__dirname, 'src/index.html'),
protocol: 'file:',
slashes: true,
})
);
var menu = Menu.buildFromTemplate([
{
label: 'File',
submenu: [
{
label: 'Open File',
click() {
openFile();
},
accelerator: 'CmdOrCtrl+O',
}
]
}]);
Menu.setApplicationMenu(menu);
}
app.on('ready', createWindow);
index.js:
const { dialog } = require('electron').remote;
function openFile() {
dialog.showOpenDialog({
title: 'Open File',
properties: ['openFile'],
});
}
module.exports = {
openFile,
};
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="styles/style.css" />
<title>Stonecutter</title>
</head>
<body>
<script src="./index.js"></script>
</body>
</html>
Error:
When I do the same thing but without the required the code works fine:
// index.js
// --------
// This code works
function openFile() {
console.log('Open file');
}
module.exports = {
openFile,
};
// Main.js is the same
You're using a remote inside the main process. This is what causes the problem. Remote is what you use from Renderer process (scripts required from a BrowserView). So you need to write two different openFile functions for main and renderer processes.
So when you require index.js from main.js this is what cause the error. You need determine where you are in the main process or in the renderer. Watch open-file.js below to see how to do it.
All together it should look like this:
main.js
const { app, BrowserWindow, Menu } = require('electron');
const url = require('url');
const path = require('path');
const {openFile} = require('./open-file')
let win;
function createWindow() {
win = new BrowserWindow({
width: 800,
height: 600,
icon: __dirname + 'src/styles/media/icon.ico',
webPreferences: {
nodeIntegration: true,
enableRemoteModule: true,
},
});
win.loadURL(
url.format({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file:',
slashes: true,
})
);
}
app.on('ready', () => {
createWindow()
var menu = Menu.buildFromTemplate([
{
label: 'File',
submenu: [
{
label: 'Open File',
click() {
openFile();
},
accelerator: 'CmdOrCtrl+O',
}
]
}]);
Menu.setApplicationMenu(menu);
})
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="styles/style.css" />
<title>Stonecutter</title>
</head>
<body>
<button id="open-file">Open file</button>
<script>
const {openFile} = require('./open-file.js')
document.querySelector('#open-file').addEventListener('click', () => openFile())
</script>
</body>
</html>
open-file.js
const electron = require('electron');
// electron.remote for Renderer Process and electron for Main Process
const {dialog} = (electron.remote || electron)
function openFile() {
dialog.showOpenDialog({
title: 'Open File',
properties: ['openFile'],
});
}
module.exports = {
openFile,
};
This examples works as you expect. File open-file.js is what you have in index.js.
This is so because Electron runs its parts in different processes: the first is the Main process. It is where you're getting when running electron main.js. The second is a Renderer process is running in a separate os process. This is where you get calling win.loadURL() and it has slightly different API and set of libraries.

Categories