I have this electron.js app and I would like the application to close when I click on the text with class closer. Here is my code:
HTML
<!DOCTYPE html>
<html>
<head>
<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'">
<title>Hello World!</title>
<link rel="stylesheet" href="../style.css">
</head>
<body>
<div class="content">
<h1>Hello</h1>
<h1 class="closer">UUUU</h1>
</div>
<script src="./renderer.js"></script>
<script src="./closer.js"></script>
</body>
</html>
main.js initialization electron
const {app, BrowserWindow} = require('electron')
const path = require('path')
function createWindow () {
// Create the browser window.
const mainWindow = new BrowserWindow({
width: 1200,
height: 600,
backgroundColor: "red",
frame: false,
webPreferences: {
nodeIntegration: true,
preload: path.join(__dirname, 'preload.js')
}
})
// and load the index.html of the app.
mainWindow.loadFile('index.html')
// mainWindow.webContents.openDevTools()
}
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()
})
closer.js
const { app } = require('electron');
const babi = function(){
const bubu = document.querySelector('.closer');
function bubub(){
bubu.innerHTML = "aganim";
app.quit();
}
bubu.addEventListener('click', bubub);
}
babi();
My problem is that clicking the button, doesn't work. What should I do?
[...bubu].forEach(bubu =>
bubu.addEventListener("click", bubuClose())
);
function bubuClose() {
bubu.innerHTML = "aganim";
window.close();
};
I think you can do it with a loop like this.
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
I'm working on setting up my dev machine to do Electron development in VS Code.
I've been following a Hello World sample.
The problem is that the .js file inside a tag isn't being loaded. I put an alert() in an inline tag in the same html file and the alert fired correctly.
When I debug, the index.js file isn't being loaded at all.
This is my main.js
const { app, BrowserWindow, Menu } = require('electron')
const path = require('path')
const url = require('url')
const shell = require('electron').shell
let win
function createWindow () {
win = new BrowserWindow({ width: 800, height: 600})
win.loadURL(url.format({
pathname: path.join(__dirname,'src/index.html'),
protocol: 'file',
slashes: true
}))
// win.webContents.openDevTools()
win.on('closed', () => {
win = null
})
var menu = Menu.buildFromTemplate([
{
label: 'File',
submenu: [
{
label: 'Sign In To SL',
click() {
shell.openExternal('https://stackoverflow.com')
}
},
{type: 'separator'},
{
label: 'Exit',
click() { app.quit() }
}
]
}
]
)
Menu.setApplicationMenu(menu)
}
app.on('ready', createWindow)
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') app.quit()
})
app.on('activate', () => {ok
if (win == null) {
createWindow()
}
})
This is the HTML for index.html
<!DOCTYPE html>
<html>
<head>
<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'">-->
<title>Souper Grouper</title>
<link rel="stylesheet" href="../assets/css/main.css">
</head>
<body>
<div class="row">
<div id="userinfo-container">
<p class="subtext">User Name:</p>
<h1 id="username">Not Signed In</h1>
</div>
<div id="signin-container">
<button id="signinBtn">Sign In</button>
</div>
</div>
<script src="index.js"></script>
</body>
</html>
This is index.js
const electron = require('electron')
const path = require('path')
const BrowserWindow = electron.remote.BrowserWindow
const signinBtn = document.getElementById('signinBtn')
signinBtn.addEventListener('click', function(event){
alert("fired")
const modalPath = path.join('file://', __dirname, 'signin.html')
let win = new BrowserWindow({ frame: false, width: 400, height: 200})
win.on('close', function() { win = null})
win.loadURL(modalPath)
win.show()
})
I've double checked the VSCode Trust Center and the folder above my App is Trusted.
Thanks!
My HTML file isn't loading at the tutorial says it would've. This is what I have. Yes, I've tried doing all sorts of funky stuff involving paths and it doesn't fix the issue.
main.js
const { app, BrowserWindow } = require('electron');
const path = require("path");
const createWindow = () => {
const win = new BrowserWindow({
width: 800,
height: 600
})
win.loadFile("index.html")
}
app.whenReady().then(() => {
createWindow()
})
index.html
<!DOCTYPE html>
<html>
<head>
<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'">
<title>Hello World!</title>
</head>
<body>
<h1>Hello World!</h1>
We are using Node.js <span id="node-version"></span>,
Chromium <span id="chrome-version"></span>,
and Electron <span id="electron-version"></span>.
</body>
</html>
You might have to change your JavaScript code to have a full path to the HTML file.
Try with the code below, it will configure Electron. In the event listening, it is creating a new BrowserWindow with no configuration (although you can add it if you like). Then, it is loading the full path to the HTML file.
const electron = require("electron");
const {
app,
BrowserWindow
} = electron;
app.on("ready", () => {
const mainWindow = new BrowserWindow({});
mainWindow.loadURL(`file://${__dirname}\\index.html`);
});
Code:
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'">
<link rel="stylesheet" type="text/css" href="index.css">
<title>Youtify</title>
</head>
<body>
<div id = "leftBar"></div>
<div id = "rightBar"></div>
<div id = "bottomBar"><hr></div>
<div id = "toolButtons">
<div id ="closeBtn"><a data-text="✖"></a></div>
<div id="maxBtn"><a data-text="❐" ></a></div>
<div id="minBtn"><a data-text="─" ></a></div>
</div>
<script src="./renderer.js"></script>
</body>
</html>
main.js
const {app, BrowserWindow, ipcMain} = require('electron') const path = require('path')
function createWindow () { const mainWindow = new BrowserWindow({
width: 800,
height: 600,
frame: false, })
mainWindow.loadFile('index.html') }
app.whenReady().then(() => { createWindow()
app.on('activate', function () {
if (BrowserWindow.getAllWindows().length === 0) createWindow() }) })
renderer.js
// close app
function closeApp(e) {
e.preventDefault();
app.quit();
}
document.getElementById("closeBtn").addEventListener("click", closeApp);
What I want is to click on the button with the id "closeBtn" to close the app, I was looking for it, but I just can't make it working.
Can anyone please help?
Try using ipcRenderer to send the close command to main.js
In your main.js:
ipcMain.on('close', () => {
app.quit()
})
Then, in your renderer.js:
const ipc = require('electron').ipcRenderer
// close app
function closeApp(e) {
e.preventDefault()
ipc.send('close')
}
document.getElementById("closeBtn").addEventListener("click", closeApp);
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.