How to use contextBridge in React-Electron? - javascript

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...

Related

Can I fire Phaser 3 events from DOM?

I'm trying to fire a Phaser 3 event from DOM like I read on this example I found on internet:
"The game instance is accessible when you create the game, with something like
const game = new Phaser.Game(config);
And you can access everything from your desired scene from this instance
const scene = game.scene.keys.sceneName
And do something like
textareaElement.addEventListener("change", function(event) {
const text = textareaElement.value;
scene.updateGameTextFromTextarea(text);
});
This is my project config:
const config = {
// Phaser.AUTO, intenta usar WebGL y si el navegador no lo tiene, usa canva.
type: Phaser.AUTO,
parent: 'game-container',
width: 650,
height: 522,
scene: [MainScene],
scale: {
mode: Phaser.Scale.FIT
},
dom: {
createContainer: true
},
physics: {
default: 'arcade',
arcade: {
// debug: true,
// gravity: { y: 350 }
}
}
}
// Inicializacion del objeto
game = new Phaser.Game(config)`
I actually can access to game from console, but canĀ“t fire events.
const scene = game.scene.keys.MainScene
scene.greeting()
get:
Uncaught TypeError: Cannot read properties of undefined (reading 'greeting')
at :1:7
Code:
https://github.com/Neffer2/bull-rompecabezas.git
There are two issues:
The first issue is, that the name of the scene is gameScene not MainScene , this is the value from the constructor.
The second issue is the Scene/Game Instance is not populated right away, you would have to wait abit. I simulated this in the demo with the setTimeout, or you can also click the Button to call the same function from the scene.
Here a short Demo:
document.body.style = 'margin:0;';
class MainScene extends Phaser.Scene {
constructor(){
super('gameScene');
}
test(){
console.info('Hello From Scene');
}
}
var config = {
type: Phaser.AUTO,
width: 536,
height: 183,
physics: {
default: 'arcade',
arcade: {
gravity:{ y: 100 },
debug: true
}
},
scene: [ MainScene ],
banner: false
};
var game = new Phaser.Game(config);
setTimeout( () => game.scene.keys.gameScene.test(), 1000); // Wait for generation
document.querySelector('button').addEventListener('click', () => game.scene.keys.gameScene.test())
<script src="//cdn.jsdelivr.net/npm/phaser#3.55.2/dist/phaser.js"></script>
<button id="button"> Fire from the DOM </button><br>

Electron, calling dialog.showMessageBox in renderer process

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"
})
}
}
)

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();
})

I have an electron app but the print button is not working

I have an electron app I wrote for my website that just opens the website. My website uses jQuery data tables and I have a button that I click that opens a new tab with the table as a pdf and prints it. When I try to use the button on electron it opens a new white window and nothing shows up, but it works on my website. I'm new to electron so sorry if this is a super simple fix, but I couldn't seem to find anything online for this, maybe I'm searching incorrectly. Is there any way I can get the electron app to work with my print button. The print method I'm using is a built in jQuery function.
My electron code:
const { app, BrowserWindow } = require('electron')
function createWindow () {
let win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: false
}
})
win.loadURL('mywebsiteurl')
win.webContents.openDevTools()
}
app.on('ready', createWindow)
And my code for the data table printing
table = $('#studentstable').DataTable({
"aaData": data,
"dom": 'Bfrtip',
"buttons": ['print'],
"aoColumns": [
{ "mData": "studentid"},
{ "mData": "name"},
{ "mData": "phone"},
{ "mData": "grade"},
{ "mData": "category"},
{ "mData": "totalHours"},
{ "mData": "studentid",
"render": function(data, type, row, meta) {
if(type === 'display') {
//data = 'Edit' +
data = 'Add Hours' +
' Delete' +
' Report';
}
return data;
}
}],
"paging":true,
"pageLength":20,
"ordering":true
});
Let me know if you want me to add anything else and I can send it
Thank you!
Just activate the nativeWindowOpen state
will be enough
const { app, BrowserWindow } = require('electron')
function createWindow () {
let win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true,
nativeWindowOpen: true, //**** add this**
}
})
win.loadURL('yoursite')
win.webContents.openDevTools()
}
app.on('ready', createWindow)

How to fix application-window resizing error for a BrowserView in electronjs?

so I'm writing on a electron application at the moment.
To make my application a bit smoother I created a BrowserWindow and loaded just the menubar and the background.
After that I added a BrowserView to show the acutal content.
Code for my BrowserWindow:
function createWindow() {
win = new BrowserWindow({
width: 800,
height: 600,
show: false,
frame: false,
webPreferences: {
nodeIntegration: true
}
})
win.loadFile(path.join(__dirname, 'views/index.pug'));
win.on('closed', () => {
win = null;
})
win.once('ready-to-show', () => {
win.show();
})
}
Code for my BrowserView:
function createViews() {
contentView = new BrowserView({ webPreferences: { nodeIntegration: true } });
win.addBrowserView(contentView);
contentView.setBounds({ x: 0, y: 23, width: win.getBounds().width, height: win.getBounds().height - 23 });
contentView.setAutoResize({ width: true, height: true });
contentView.webContents.loadFile(path.join(__dirname, 'views/imageGallery.pug'));
}
(If there is a spoiler function to hide the code: I'm sorry, I didn't find any)
Once I create the window it works like intended, also the normal resize via mouse-drag works perfectly.
Now my problem is, as soon as I maximize or unmaximize my window with the functions win.maximize() and win.unmaximize() my BrowserView gets resized. But the resize doesn't fit the BrowserWindow anymore. The content of the BrowserView is being cutted on the right side.
Window after being maximized:
Window after being unmaximized:
function createWindow() {
// Create the browser window.
const mainWindow = new BrowserWindow({ useContentSize: true });
const view = new BrowserView();
mainWindow.setBrowserView(view);
view.setBounds({ x: 0, y: 0, width: 800, height: 600 });
view.setAutoResize({ width: true, height: true });
view.webContents.loadURL("https://youtube.com");
}

Categories

Resources