Im new in this electron space, and have a problem. i didn´t manage to get my custom buttons to work. This drives me crazy. Anyone an idea what i´m doing wrong? the Buttons do simply nothing when i click. My code is an example from an older youtube Tutorial, and i think things have changed since then.
Here is my code:
menuHandler.js
const $ = require('jquery');
const { remote } = require('electron');
var win = remote.getCurrentWindow();
$('#minimize').click(function () {
win.minimize();
});
$('#close').click(function () {
win.close();
});
$('#maximize').click(function () {
if (win.isMaximized()) {
win.unmaximize();
} else {
win.maximize();
}
console.log(win.isMaximized());
});
my index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="css/reset.css" rel="stylesheet">
<link href="css/menu.css" rel="stylesheet">
<script type ="text/javascript"> src="/src/js/menuHandler.js"</script>
</head>
<body>
<div id="container">
<nav>
<div id="buttons">
<div id="minimize">
<span id="minimize-font">—</span>
</div>
<div id="maximize">
<span id="size-font">◻</span>
</div>
<div id="close">
<span id="close-font" >✕</span>
</div>
</div>
</nav>
</div>
</html>
</body>
</html>
and my app.js
const { app, BrowserWindow } = require('electron');
const path = require('path');
const url = require('url');
let win;
var IMG_DIR = '/img/';
var APP_DIR = '/src/';
function createWindow() {
win = new BrowserWindow({
width: 1100,
height: 750,
minWidth: 930,
minHeight: 650,
frame: false,
/*title: "Nader | Initio",
resizable: true, */
backgroundColor: '#1A373E',
icon: path.join(__dirname, IMG_DIR, 'icon.png'),
webPreferences: {
nodeIntegration: true
}
});
win.openDevTools()
win.loadURL(url.format({
pathname: path.join(__dirname, APP_DIR, 'index.html'),
protocol: 'file:',
slashes: true
}))
}
app.on('ready', createWindow);
app.on('window-all-closed', () => {
if(process.platform !== 'darwin') {
app.quit();
}
});
thank you for your help!
Several small things are needed to make your code work:
<script type ="text/javascript"> src="/src/js/menuHandler.js"</script>
needs to be
<script type="text/javascript" src="/src/js/menuHandler.js"></script>
Since Electron 10, released in August 2020, you need to set enableRemoteModule: true in the webPreferences if you want to use remote in the renderer process.
Lastly, you should register the button click event handlers after the page is loaded. Otherwise, chances are the elements don't exist yet.
$(window).on("load", function() {
console.log("loaded");
$("#minimize").click(function () {
console.log("minimize");
win.minimize();
});
// etc.
});
As a general tip I'd advise to make use of the DevTools, which you already activate in your code. There, in the Console tab, you can see JavaScript errors happening in the renderer process.
Related
I want to create an electron.js app. The first window that opens should be a login window. But now I have the problem that I can't manage that when I press the login button the new main window opens.
At the moment I always get the error: Uncaught ReferenceError: require is not defined
at createBrowserWindow (login.js:16)
at HTMLFormElement. (login.js:9)
Here is my main.js file
// main.js
// Modules to control application life and create native browser window
const { app, BrowserWindow } = require('electron')
const path = require('path')
function createLoginWin() {
const loginWindow = new BrowserWindow({
width: 300,
height: 500,
minWidth: 300,
minHeight: 500,
maxWidth: 300,
maxHeight: 500,
icon: path.join(__dirname, 'assets/images/command.png'),
webPreferences: {
preload: path.join(__dirname, 'preload_login.js')
}
})
loginWindow.loadFile('./src/index.html');
loginWindow.setMenuBarVisibility(false);
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
createLoginWin()
app.on('activate', () => {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (BrowserWindow.getAllWindows().length === 0) createWindow()
})
})
// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') app.quit()
})
It is basically the file from the electron.js documentation.
Here is my html file:
<!--index.html-->
<!DOCTYPE html>
<html>
<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'">
<title>Document</title>
</head>
<body>
<div id="container">
<form id="login-form">
<input type="text" placeholder="Username or Email" id="username_in">
<input type="password" placeholder="password" id="password_in">
<button type="submit" id="submit_btn">Login</button>
</form>
</div>
<script src="./login.js"></script>
</body>
</html>
And here is my login.js file:
const loginForm = document.getElementById('login-form')
loginForm.addEventListener("submit", (event) => {
event.preventDefault();
const test = document.getElementById('container')
test.style.backgroundColor = 'black';
console.log('TestHTML')
createBrowserWindow();
console.log('TestHTML2')
});
function createBrowserWindow() {
console.log('TestJS1')
const remote = require('electron').remote;
console.log('TestJS2')
const BrowserWindow = remote.BrowserWindow;
const win = new BrowserWindow({
height: 600,
width: 800,
webPreferences: {
nodeIntegration: true
}
});
win.loadFile('./index.html')
win.show()
}
const loginForm = document.getElementById('login-form')
loginForm.addEventListener("submit", (event) => {
event.preventDefault();
const test = document.getElementById('container')
test.style.backgroundColor = 'black';
console.log('TestHTML')
createBrowserWindow();
console.log('TestHTML2')
});
function createBrowserWindow() {
console.log('TestJS1')
const remote = require('electron').remote;
console.log('TestJS2')
const BrowserWindow = remote.BrowserWindow;
const win = new BrowserWindow({
height: 600,
width: 800,
webPreferences: {
nodeIntegration: true
}
});
win.loadFile('./index.html')
win.show()
}
I have one website link which currently is working when clicking the link a window pop-up, but I want the onclick to happen automatically without clicking. The onclick should work like onload.
I tried a lot of Google and StackOverflow searches.. but I couldn't find the exact solution to my problem.
Here's my code below:
<!DOCTYPE html>
<html>
<head>
<title>mygame | Browser</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<script type="text/javascript" src="../api.js"></script>
<script type="text/javascript">
function initialize() {
document.getElementById('robrowser').addEventListener("click", function(){
var ROConfig = {
type: ROBrowser.TYPE.POPUP,
application: ROBrowser.APP.ONLINE,
remoteClient: "http://play.mygame.com/client",
width: 1024,
height: 768,
development: false,
servers: [{
display: "mygame",
desc: "mygame Revolution",
address: "94.99.190.98",
port: 6900,
version: 46,
langtype: 12,
packetver: 20170614,
packetKeys: false,
socketProxy: "ws://196.66.646.179:5999/"
}],
saveFiles: true,
skipServerList: true,
skipIntro: true,
version: 1,
plugins: {
IntroMessage: {}
}
};
var RO = new ROBrowser(ROConfig);
RO.start();
}, false );
}
window.addEventListener("load", initialize, false);
</script>
</head>
<body>
<input type="button" value="Run roBrowser" id="robrowser"/>
</body>
You can simulate a buttonclick like this:
$("#robrowser").click();
In this case you want to run the method when a page is loaded.
You can just remove the entire onclick listener and call the function initialize() directly:
function initialize() {
var ROConfig = {
type: ROBrowser.TYPE.POPUP,
application: ROBrowser.APP.ONLINE,
remoteClient: "http://play.mygame.com/client",
width: 1024,
height: 768,
development: false,
servers: [{
display: "mygame",
desc: "mygame Revolution",
address: "94.99.190.98",
port: 6900,
version: 46,
langtype: 12,
packetver: 20170614,
packetKeys: false,
socketProxy: "ws://196.66.646.179:5999/"
}],
saveFiles: true,
skipServerList: true,
skipIntro: true,
version: 1,
plugins: {
IntroMessage: {}
}
};
var RO = new ROBrowser(ROConfig);
RO.start();
}
initialize();
The following changes have been made:
button on click event listener moved into the window load function
The source code from the button click event moved into initialize()
button on click event to target the function initialize
window load function calls/executes initialize()
Source code:
<!DOCTYPE html>
<html>
<head>
<title>mygame | Browser</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<script type="text/javascript" src="../api.js"></script>
<script type="text/javascript">
function initialize() {
var ROConfig = {
type: ROBrowser.TYPE.POPUP,
application: ROBrowser.APP.ONLINE,
remoteClient: "http://play.mygame.com/client",
width: 1024,
height: 768,
development: false,
servers: [{
display: "mygame",
desc: "mygame Revolution",
address: "94.99.190.98",
port: 6900,
version: 46,
langtype: 12,
packetver: 20170614,
packetKeys: false,
socketProxy: "ws://196.66.646.179:5999/"
}],
saveFiles: true,
skipServerList: true,
skipIntro: true,
version: 1,
plugins: {
IntroMessage: {}
}
};
var RO = new ROBrowser(ROConfig);
RO.start();
}
window.addEventListener("load", function(){
document.getElementById('robrowser').addEventListener("click", initialize, false );
initialize();
}, false);
</script>
</head>
<body>
<input type="button" value="Run roBrowser" id="robrowser"/>
</body>
</html>
If you have any questions about the source code above please leave a comment below and I will get back to you as soon as possible.
I hope this helps, happy coding!
i am trying to load assets on javascript using phaser3 engine but on chrome consol it says 'failed to load image' here is my HTML & Javascript code look where i made mistake:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>PhaserGame</title>
<script = "text/javascript" src = "phaser.js"></script>
</head>
<body>
<script src="script.js"></script>
</body>
</html>
JAVASCRIPT:
var config = {
type: Phaser.AUTO,
width: 800,
height: 600,
physics: {
default: 'arcade',
arcade: {
gravity: {y: 500},
debug: false
}
},
scene: {
preload: preload,
create: create,
update: update
}
};
var game = new Phaser.Game(config);
function preload() {
this.load.image('sky','assets/sky.png');
}
function create() {
this.add.image(400, 300, 'sky');
}
function update() {
}
I think there is some problem with your image location
the same code worked for me, with only changing the image URL
https://codepen.io/devsumanmdn/pen/zaeZwJ?editors=0010
create folder "public" in project and put images here
I have created an electron application that has multiple windows that can open ex. an about page and a preferences page. This is what my main.js looks like.
const {app, Tray, Menu, BrowserWindow} = require('electron');
//electron application stuff
const path = require('path'); //allows for use of path
const url = require('url'); //allows for loadURL and url.format
const iconPath = path.join(__dirname, 'icon.png'); //grab the icon
let tray = null; //set the tray to null
let win = null; //set the main window to null
app.on('ready', function(){
win = new BrowserWindow({width: 600, height: 400, resizable: false});
//create main window
win.setMenu(null); //the main window had no menu
win.loadURL(url.format({ //loads the webpage for the main window
pathname: path.join(__dirname, 'index.html'),
protocol: 'file:',
slashes: true
}))
win.openDevTools(); //starts the application with developer tools open
win.on('minimize',function(event){ //prevents standard minimize
function of a main window
event.preventDefault()
win.hide();
});
win.on('close', function (event) { //prevents the closing of the
aplication when the window closes
if( !app.isQuiting){
event.preventDefault()
win.hide();
}
return false;
});
tray = new Tray(iconPath); //create a new tray
var contextMenu = Menu.buildFromTemplate([ //start buliding out the
menu for the tray
{ label: 'Insomnia', click: function(){ //makes the main window reappear
win.show();
} },
{ label: 'About', click: function(){ //shows the about window
abt = new BrowserWindow({width: 400, height: 400, resizable: false});
abt.setMenu(null); //the about window has no menu
abt.loadURL(url.format({ //loads the webpage for the about window
pathname: path.join(__dirname, 'about.html'),
protocol: 'file:',
slashes: true
}))
} },
{
label: 'Preferences', click: function(){ //shows the about window
pref = new BrowserWindow({width: 400, height: 400, resizable: false});
pref.setMenu(null); //the about window has no menu
pref.loadURL(url.format({ //loads the webpage for the about window
pathname: path.join(__dirname, 'preferences.html'),
protocol: 'file:',
slashes: true
}))
}
},
{ label: 'Quit', click: function(){ //quit the application
app.isQuiting = true;
app.quit(); //quit called
} }
]);
tray.setToolTip('Insomnia'); //Honestly no clue but itll make the tray
say insomnia in some other place
tray.setContextMenu(contextMenu); //attach the menu to the tray
});
When the user opens the preferences window I have a button there that lets them store their preferences. When i use scripts from the java script file on win window they actually work. However using that same logic for the preferences window none of the java script functions actually run. This is what my preferences.html looks like
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Preferences</title>
</head>
<body BGCOLOR="#02D9CC" >
</div>
<center> <img src="sleep.png" alt="sleep" style="width:100px;height:100px;"> </center>
<div style="position:absolute;bottom:250px;margin-left:110px">
<center>
<input onclick="storeTimePreference()" type="radio" id="timeType" name="timeType" value="Military"> Military </input>
<input onclick="storeTimePreference()" type="radio" id ="timeType2" name="timeType" value="Standard" checked="checked"> Standard </input>
</center>
</div>
<div style="position:absolute;bottom:150px;margin-left:110px">
<center><input type="time" id="defaultTime" /><br>
<button onlick="readFile()" >Set Default Wake Up Time</button>
</center>
</div>
<div class ="version" style="position:absolute;bottom:5px;color:white;margin-left:225px">
<center >
Insomnia Version 1.0.0
</center>
</div>
<script src="./js/script.js"></script>
</body>
</html>
Where the readFile() script and storeTimePreference() functions are both part of the script.js included at the bottom. Which is the same way i did it for the index.html however here it doesn't work and I'm not sure why. Can anyone explain what I'm doing wrong here or why this doesn't work and what a workaround would be?
I am following the example in "Creating a new OpenUI5 Component" from the OpenUI docs, and when I run my demo page I am getting an error in the Chrome console that reads:
Uncaught Error: The specified component controller 'my.components.button.Component' could not be found!
I can navigate to 'localhost:3000/components/button/Component.js' and see the contents of the JS file. So the file exists, so i guess i am not referencing it correctly in my code (or have an unfortunate typo somewhere). How should i be referencing the component?
My folder structure looks like this:
folder structure
webapp
components
button
Within the button folder I have Component.js and Component.json.
Component.js looks like this:
jQuery.sap.require("sap.ui.core.UIComponent");
jQuery.sap.require("sap.ui.commons.Button");
jQuery.sap.declare("components.button.Component");
// new Component
sap.ui.core.UIComponent.extend("components.button.Component", {
metadata: {
properties: {
text: "string"
}
},
init: function() {
sap.ui.core.UIComponent.prototype.init.apply(this, arguments);
}
});
components.button.Component.prototype.createContent = function () {
this.oButton = new sap.ui.commons.Button("btn");
return this.oButton;
};
components.button.Component.prototype.setText = function (sText) {
this.oButton.setText(sText);
this.setProperty("text", sText);
return this;
};
And Index.html looks like this:
<!DOCTYPE html >
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta charset="utf-8">
<title>Component Test</title>
<script
id="sap-ui-bootstrap"
src="https://openui5.hana.ondemand.com/resources/sap-ui-core.js"
data-sap-ui-theme="sap_bluecrystal"
data-sap-ui-libs="sap.m"
data-sap-ui-compatVersion="edge"
data-sap-ui-preload="async"
data-sap-ui-resourceroots='{
"my": "./"
}' >
</script>
<script>
sap.ui.getCore().attachInit(function () {
var oComp1 = sap.ui.getCore().createComponent({
name: "my.components.button",
id: "Comp1",
settings: {text: "Hello World"}
});
// place this Ui Container with the Component inside into UI Area
oCompCont1.placeAt("target1");
var oCompCont2 = new sap.ui.core.ComponentContainer("CompCont2", {
name: "my.components.button",
settings: {text: "Hello World again"}
});
oCompCont2.placeAt("target2");
});
</script>
</head>
<body class="sapUiBody">
<div id="target1"></div>
<div id="target2"></div>
</body>
</html>
The correct answer was provided by #deterministicFail in the comments to the original question. I am providing the updated/corrected code here for completeness
Corrected Component.js
jQuery.sap.require("sap.ui.core.UIComponent");
jQuery.sap.require("sap.ui.commons.Button");
jQuery.sap.declare("components.button.Component");
sap.ui.core.UIComponent.extend("my.components.button.Component", {
metadata: {
properties: {
text: "string"
}
},
init: function() {
sap.ui.core.UIComponent.prototype.init.apply(this, arguments);
}
});
my.components.button.Component.prototype.createContent = function () {
this.oButton = new sap.ui.commons.Button("btn");
return this.oButton;
};
my.components.button.Component.prototype.setText = function (sText) {
this.oButton.setText(sText);
this.setProperty("text", sText);
return this;
};
Corrected Index.html
<!DOCTYPE html >
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta charset="utf-8">
<title>Component Test</title>
<script
id="sap-ui-bootstrap"
src="https://openui5.hana.ondemand.com/resources/sap-ui-core.js"
data-sap-ui-theme="sap_bluecrystal"
data-sap-ui-libs="sap.m"
data-sap-ui-compatVersion="edge"
data-sap-ui-preload="async"
data-sap-ui-resourceroots='{
"my": "./"
}' >
</script>
<script>
sap.ui.getCore().attachInit(function () {
jQuery.sap.registerModulePath("my.components.button", "components/button");
var oComp1 = sap.ui.getCore().createComponent({
name: "my.components.button",
id: "Comp1",
settings: {text: "Hello World"}
});
// Create a Ui container
var oCompCont1 = new sap.ui.core.ComponentContainer("CompCont1", {
component: oComp1
})
// place this Ui Container with the Component inside into UI Area
oCompCont1.placeAt("target1");
var oCompCont2 = new sap.ui.core.ComponentContainer("CompCont2", {
name: "my.components.button",
settings: {text: "Hello World again"}
});
oCompCont2.placeAt("target2");
});
</script>
</head>
<body class="sapUiBody">
<div id="target1"></div>
<div id="target2"></div>
</body>
</html>