I want close electron app from another html page with button - javascript

We are currently improve a project with electronjs: We have main.js for electron as you know and we have another html page that javascripts codes in it. We created a close button in this html page and this button should close the app but we cant reach main.js for close the app. Can you help me?
This code is from html page :
<div class="background-three link-container">
<button class="link-three" onclick="kapat()" id="kptbtn">Kapat</button>
</div>
<script>
function kapat(){
//what should I write here.
}
</script>
and this main.js
const { app, BrowserWindow } = require('electron')
const path = require('path')
function createWindow() {
const win = new BrowserWindow({
transparent: true,
frame: false,
resizable: false,
width: 500,
height: 700,
webPreferences: {
preload: path.join(__dirname, 'preload.js')
}
})
win.loadFile('girisEkrani.html')
}
app.whenReady().then(() => {
createWindow()
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow()
}
})
})
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})

You must use ipcMain and ipcRenderer. Main for reading message and Renderer for sending message.
.html page
<script>
function kapat() {
const { ipcRenderer } = require('electron')
const ipc = ipcRenderer;
ipc.send('kapat');
}
...
</script>
if you define ipc stuff out of the function it will not work and effect other functions.
main.js
const { app, BrowserWindow, ipcMain } = require('electron')
const path = require('path')
const ipc = ipcMain;
function createWindow() {
const win = new BrowserWindow({
transparent: true,
frame: false,
resizable: false,
width: 500,
height: 700,
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
}
})
ipc.on('kapat', () => { win.close() })
win.loadFile('girisEkrani.html')
}

Related

Electron - How to pass data to renderer from a new opened window?

I'm struggling to pass a data from newly opened site window to renderer. What I want to achieve is to find a login button on site and listen on click event. I was reading about webview in electron, but I couldn't make It work. For now I'm stuck on window.open() method. Can you please point me what aspect I am missing? Here are my files:
//main.js
const {app, BrowserWindow, ipcMain} = require('electron')
const path = require('path')
function createWindow () {
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
nodeIntegration: true,
contextIsolation: false,
enableRemoteModule: true
}
})
mainWindow.loadFile('index.html')
// Open the DevTools.
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()
})
ipcMain.on("open-login-window", () => {
console.info('dostal');
});
//renderer.js
const electron = require("electron");
const ipc = electron.ipcRenderer
const button = document.getElementById("login-button");
button.addEventListener("click", () => {
ipc.send("open-login-window")
const windowProxy = window.open('https://www.somesite.com/login', null, 'minimizable=false')
windowProxy.postMessage('hi', '*')
});

How set parameters for new windows in electron

I would like know how I can set configuration width and height in new window opened in electron above my code on main.js
const {app, BrowserWindow, webContents, session} = require('electron')
let mainWindow
function createWindow () {
mainWindow = new BrowserWindow({
width: 1000, height: 800,
webPreferences: {
contextIsolation: false,
nodeIntegration: true
}
})
mainWindow.loadFile('Control/index.html')
mainWindow.setMenu(null)
mainWindow.on('closed', () => {
mainWindow = null
})
let wc = mainWindow.webContents
wc.on('new-window', (e, url) => {
e.preventDefault()
}
}

Window object in renderer script in Electron app does not contain data from preload script

I am completely new to Electron so please forgive me if I am doing this completely wrong.
Apparently for security reasons I need to use a contextBridge to communicate between the preload and renderer scripts and the main script. I could not find a clear example for how to set this up so I took the provided answer to this stack overflow question: How to use preload.js properly in Electron. However, when I try to access window.api.receive I get the error Cannot read property 'receive' of undefined. So my window.api is undefined but I can not figure out why.
I also tried to simply set window.isWorking = true in my preload.js script and tried to print it in my renderer script like I have seen others do, but this also just prints undefined.
I use the following code:
main.js
const { app, BrowserWindow, ipcMain } = require('electron');
const path = require('path');
let win;
function createWindow() {
win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
contextIsolation: true,
nodeIntegration: false,
enableRemoteModule: false,
preload: 'preload.js'
}
});
win.loadFile('index.html');
}
app.whenReady().then(() => {
createWindow();
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
});
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
ipcMain.on("test", (event, args) => {
console.log("received test request");
win.webContents.send("test", "some data");
});
preload.js
import { ipcRenderer, contextBridge } from "electron";
contextBridge.exposeInMainWorld(
"api", {
send: (channel, data) => {
let validChannels = ["test"];
if (validChannels.includes(channel)) {
ipcRenderer.send(channel, data);
}
},
receive: (channel, func) => {
let validChannels = ["test"];
if (validChannels.includes(channel)) {
ipcRenderer.on(channel, (event, ...args) => func(...args));
}
}
}
);
window.isWorking = true;
renderer.js
console.log(window.isWorking); // prints undefined
window.api.receive("test", (data) => { // exception on trying to access window.api.receive
console.log("data", data);
});
window.api.send("test", "some data");
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 style="background: white;">
<h1>Hello World!</h1>
<script src="renderer.js"></script>
</body>
</html>
I think { contextIsolation: false; nodeIntegration: true } allows importing electron and allows to set window.something
So try writing:
win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
contextIsolation: false,
nodeIntegration: true,
preload: 'preload.js'
}
});

Unable to disable fullscreen and block size of the windows in Electron JS

I'm new to Electron Js and i've tried all the snippets that i could find, but i'm still unable to disable the possibilities to enlarge the window to a full screen size. I'm running the last version of Electron Js and Windows 10.
Here is the source code :
const { app, BrowserWindow } = require('electron')
try {
require('electron-reloader')(module)
} catch (_) {} //For dev purposes only
function createWindow () {
const win = new BrowserWindow({
width: 700,
height: 700,
webPreferences: {
frame:false,
maximizable: false,
fullscreen: false,
nodeIntegration: true
}
})
win.setMenuBarVisibility(false)
win.loadFile('src/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()
}
})
It should work, (can you show your new BrowserWindow config...) I tested on a working app by modifying the config:
mainWindow = new BrowserWindow({
width: 850, //1200,
maxWidth:850,
minWidth:550, //1024,
height: 820,
webPreferences: webPref,
title: "MesRestau",
icon: __dirname + "/assets/images/favicon.ico"
});

How to move ipcMain.on calls outside the main.js file

I am working on a project with Electron and React. I am going to be making multiple calls to the database via ipcMain and ipcRenderer so I moved the calls for ipcMain to another file(ipcMainHandler.js).
The challenge I am facing now is how to send responses back to the ipcRenderer. I am unable to access the mainWindow from within that file.
This is the code for my main file.
const url = require('url');
const { app, BrowserWindow } = require('electron');
let mainWindow;
function createWindow() {
mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true,
enableRemoteModule: true,
preload: __dirname + '/preload.js'
},
});
const startUrl =
process.env.ELECTRON_START_URL ||
url.format({
pathname: path.join(__dirname, './build/index.html'),
protocol: 'file:',
slashes: true,
});
mainWindow.loadURL(startUrl);
mainWindow.webContents.openDevTools();
mainWindow.on('closed', function () {
mainWindow = null;
});
}
app.on('ready', createWindow);
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', function () {
if (mainWindow === null) {
createWindow();
}
});
require('./src/server/helpers/ipcMainHandler.js');
The ipcMainHandler.js file
const { SIGNIN_REQUEST, SIGNIN_RESPONSE } = require('../../common/events.js');
const { ipcMain } = require('electron');
ipcMain.on(SIGNIN_REQUEST, (event, data) => {
const user = AuthController.userSignin({ ...data });
});
Things I have tried
Accessing the currentWindow from remote - throws a remote undefined error
Adding the mainWindow to a global variable and trying to access it in the ipcHander. - This also returns an undefined message.
This has been resolved. I used the event object to send the response from ipcMain.
ipcMain.on(SIGNIN_REQUEST, async (event, data) => {
const user = await AuthController.userSignin({ ...data });
event.sender.send(SIGNIN_RESPONSE, user);
});

Categories

Resources