Electron, calling dialog.showMessageBox in renderer process - javascript

Trying to get my head around getting a dialog.showMessageBox() in the render process using preload. I'm trying const {dialog} = require( 'electron') but it's returning undefined. What am I missing?
main.js:
const consoleWindow = new BrowserWindow({
title: 'TakServer | Console',
width: DEBUG ? 1000 : 800,
height: 600,
resizable: true,
alwaysOnTop: true,
show: false,
webPreferences: {
nodeIntegration: false,
contextIsolation: true, n
enableRemoteModule: false,
preload: path.join(__dirname, "preload.js")
}
})
preload.js:
const { contextBridge, dialog } = require("electron");
console.log( "dialog", dialog ) // !! undefined
contextBridge.exposeInMainWorld( 'api',
{
test: ( x ) => {
const {fs} = require( 'fs' )
console.log( "gubbmins", fs )
dialog.showMessageBox( {
type: "info",
message: "stuff"
})
}
}
)

Related

Uncaught Error: no element is specified to initialize PerfectScrollbar

The error detailed Uncaught Error: no element is specified to initialize PerfectScrollbar
version: perfect-scrollbar v1.5.3
Error from my web browser console
pscroll.js
(function ($) {
"use strict";
*const ps = new PerfectScrollbar(".app-sidebar", {
useBothWheelAxes: true,
suppressScrollX: true,
suppressScrollY: false,
});
const ps1 = new PerfectScrollbar(".header-dropdown-list", {
useBothWheelAxes: true,
suppressScrollX: true,
suppressScrollY: false,
});
const ps2 = new PerfectScrollbar(".notifications-menu", {
useBothWheelAxes: true,
suppressScrollX: true,
suppressScrollY: false,
});
const ps3 = new PerfectScrollbar(".message-menu-scroll", {
useBothWheelAxes: true,
suppressScrollX: true,
suppressScrollY: false,
});
//P-scrolling
*})(jQuery);
pscroll-1.js
(function($) {
"use strict";
*const ps11 = new PerfectScrollbar('.sidebar-right', {
useBothWheelAxes: true,
suppressScrollX: true,
});
*})(jQuery);
I marked the error line into *.
After you posted the html, the only class I could find within the document was app-sidebar. Can you confirm you are not missing these classes within the html?
header-dropdown-list
notifications-menu
message-menu-scroll
sidebar-right

in case i have multiple monaco diff editor in the same page, diff will be only visible in the first instance

I have a Vue component that rendering diff editor of Monaco.
Once I have more than one instance of it on the same page, the diff is only shown in the first one.
template:
<template>
<div>
<div ref="diffEditor" class="vue--monaco-diff-editor"></div>
</div>
</template>
script:
async mounted(): Promise<void> {
await this.importMonacoPackage();
this.$nextTick(() => {
if (!monaco) {
throw new Error('monaco is not initialized');
}
const originalModel = monaco.editor.createModel(
this.versions[0].code,
MonacoHelper.markdownLangToMonacoLang(this.versions[0].lang),
);
const modifiedModel = monaco.editor.createModel(
this.versions[1].code,
MonacoHelper.markdownLangToMonacoLang(this.versions[1].lang),
);
let diffEditorElement = this.$refs.diffEditor;
this.diffEditor = monaco.editor.createDiffEditor(
diffEditorElement as HTMLElement,
{
scrollbar: {
vertical: 'hidden',
horizontal: 'hidden',
handleMouseWheel: true,
},
wordWrap: 'on',
readOnly: true,
scrollBeyondLastLine: false,
minimap: {
enabled: false,
},
automaticLayout: true,
},
);
if (!this.diffEditor) {
return;
}
this.diffEditor.setModel({
original: originalModel,
modified: modifiedModel,
});
// set the editor height to scale with the content height automatically
// see https://github.com/microsoft/monaco-editor/issues/794
const originalContentHeight = this.diffEditor
.getOriginalEditor()
.getContentHeight();
const modifiedContentHeight = this.diffEditor
.getModifiedEditor()
.getContentHeight();
let contentHeight = Math.max(
originalContentHeight,
modifiedContentHeight,
);
// allow for a single empty line at the bottom, default line height is 18px
contentHeight = contentHeight + 18;
const domNode = this.diffEditor.getDomNode();
domNode.style.height = `${contentHeight}px`;
this.diffEditor.layout();
});
},
methods: {
async importMonacoPackage() {
// eslint-disable-next-line import/no-unresolved
monaco = await import('../../../lib/monaco-editor');
},
},
I'm using
"monaco-editor": "^0.24.0","vue": "^2.6.13".
any ideas what I'm doing wrong ? and why just the first instance showing the diff highlights?

How to use contextBridge in React-Electron?

I'm trying to connect with preload and frame.tsx
But, It isn't working.
frame.tsx
function handleButtonClick(id: string) {
window.electron.send("requestWindowChange", "data") // Error part
if(id === 'maximize') {
setIsMaximize(!isMaximize)
}
}
I simply add it. and...
preload.ts
import {contextBridge, ipcRenderer} from 'electron'
contextBridge.exposeInMainWorld('electron', {
send: (channel:string, data) => {
let normalChannels = ['requestWindowChange']
if (normalChannels.includes(channel)) {
ipcRenderer.send(channel, data)
}
},
receive: (channel:string, func) => {
let normalChannels = ['responseWindowChange']
if (normalChannels.includes(channel)) {
ipcRenderer.on(channel, (_event, data) => func(data))
}
}
})
Also, I'm already making 'preload.ts' to 'preload.js' by using 'tsc' command.
Finally, here is the electron.ts
mainWindow = new BrowserWindow({
height: 720,
width: 1280,
minHeight: 300,
minWidth: 450,
frame: false,
show: false,
center: true,
fullscreen: false,
kiosk: !isDev,
resizable: true,
webPreferences: {
preload: path.join(__dirname, "preload.js")
}
})
I only copy necessary part.
If you need more code, please comment here.
I really don't know why It isn't working.
Here is Error Message.
any Property 'electron' does not exist on type 'Window & typeof
globalThis'. Did you mean 'Electron'?ts(2551)
I'm trying searching and asking for a week, finally I find it.
Just add this at frame.tsx.
declare global {
interface Window {
api? : any
}
}
What a simple it is...

How to make new window appear with loading indicator while preload?

I am trying to make a window application in Electron.js. When I run it, it makes preload.js script:
const mainWindow = new BrowserWindow({
width: 500,
height: 500,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
nodeIntegration: true
}
});
I want a new window with a loading indicator to appear till preload.js not finish. How can I reach it?
create first the loading window like this:
loadingWindow = new BrowserWindow({
width: 512,
height: 384,
resizable: false,
transparent: true,
frame: false,
})
loadingWindow.loadFile('views/loading.html')
make shure that you clear this window if you close it
loadingWindow.on('closed', function () {
loadingWindow = null
});
than create your main window but hide it
const mainWindow = new BrowserWindow({
width: 500,
height: 500,
show: false, // hide this window
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
nodeIntegration: true
}
});
mainWindow.loadFile('yourFile.html');
than get the did-finish-load event to close the loading window and show the mainWindow
mainWindow.webContents.on('did-finish-load', () => {
if (loadingWindow) loadingWindow.close();
mainWindow.show();
})

Open new window from Menu

When trying to open the window from the menu, an error like this comes up: "Attemping to call a function in a renderer window that has been closed or released", but the other windows are called without any problem.
const ventana = document.getElementById("ventana");
const contrasena = document.getElementById("contra");
const remote = require("electron").remote;
const Menu = remote.Menu;
const BrowserWindow = remote.BrowserWindow;
const url = require("url");
const path = require("path");
let secundario
let recuperaVentana
let add
ventana.addEventListener("click", () => {
var usuario = document.getElementById("user").value;
var pass = document.getElementById("pass").value;
if(usuario != "" & pass != ""){
createBrowserWindow();
} else {
alert("No ha llenado los campos");
}
});
contrasena.addEventListener("click", () => {
recuperarBrowserWindow();
})
function createBrowserWindow() {
secundario = new BrowserWindow({
height: 600,
width: 800
});
secundario.loadURL(url.format({
pathname: path.join(__dirname, "./prefs.html"),
protocol: "file",
slashes: true
}));
//secundario.webContents.openDevTools();
//menu
const menuSec = Menu.buildFromTemplate(templateMenu);
Menu.setApplicationMenu(menuSec);
cerrar();
}
function recuperarBrowserWindow(){
recuperaVentana = new BrowserWindow ({
title: "Recuperar"
})
recuperaVentana.loadURL(url.format({
pathname: path.join(__dirname, "./recuperar.html"),
protocol: "file",
slashes: true
}))
recuperaVentana.setMenu(null);
}
//cerrando ventana
function cerrar(){
window.close();
}
//creando menus
const templateMenu = [
{
label: "Archivo",
submenu: [
{
label: "Nuevo",
accelerator: "Ctrl+N",
click(){
addBrowserWindow();
}
},
{
label: "Abrir",
accelerator: "Ctrl+O"
},
{
label:"Guardar",
accelerator:"Ctrl+G"
},
{
type: "separator"
},
{
label:"Salir"
}
]
},
{
label: "Ayuda"
}
];
function addBrowserWindow() {
add = new BrowserWindow({
title: "Agregar"
})
add.loadURL(url.format({
pathname: path.join(__dirname, "./agregar.html"),
protocol: "file",
slashes: true
}))
}
When trying to call the function "addBrowserWindow()" the above mentioned error is shown
This is a fairly concise version of code that creates a second window on selecting a submenu:
const electron = require('electron')
const { app, BrowserWindow, Menu } = electron
let mainWindow
let secondWindow
app.on('ready', () => {
console.log('Starting Node version: ' + process.version)
mainWindow = new BrowserWindow({
width: 1200,
height: 800,
webPreferences: {
nodeIntegration: true,
},
})
mainWindow.loadURL(`file://${__dirname}/main.html`)
mainWindow.on('closed', () => app.quit())
const mainMenu = Menu.buildFromTemplate(menuTemplate)
Menu.setApplicationMenu(mainMenu)
})
function createSecondWindow() {
secondWindow = new BrowserWindow({
width: 300,
height: 200,
title: 'Add New Todo',
})
secondWindow.loadURL(`file://${__dirname}/add.html`)
}
const menuTemplate = [
{
label: 'File',
submenu: [
{
label: 'New ToDo',
click() {
createSecondWindow()
},
},
{
label: 'Quit',
accelerator: process.platform === 'darwin' ? 'Command+Q' : 'Ctrl+Q',
click() {
app.quit()
},
},
],
},
]
if (process.platform === 'darwin') {
menuTemplate.unshift({})
}
Note that by default when you close the main window and the second window will still be present - which is weird behaviour rarely needed. The solution to that is to ensure you call app.exit() when the main window is closed.

Categories

Resources