HTML Button to call app.quit() function using electron - javascript

I recently discovered electron as a GUI "maker". I asked my programming-teacher, if it's possible to run a bash script with electron.
He gave me a link to a GitHub (sadly bought by Microsoft) and it worked with a bash-script
I recently wrote a script, which installs the Origin Launcher using wine and it workd perfectly. But now, I wanted to try to cover it with a GUI, so people who aren't familiar with the Linux Terminal have a nice-looking GUI.
Now, I watched a video on how to create an electron app. I followed it step by step, and it worked.
In my index.html document, I made two buttons, one to start the Installation, and the second one to cancel it.
I included the main.js in the head part of the html File
<head>
<title>LoriginSetup</title>
<link href="assets/css/main.css" rel="stylesheet">
<script src="main.js"></script>
</head>
And inside the Body, I used the onclick to call the function inside the main.js.
The Function is called quitApplication()
<div class="btns">
<button class="btn btnstart" id="startinstall">Start Installation</button>
<button class="btn btncancel" id="cancelinstall" onclick="quitApplication()">Cancel Installation</button>
</div>
I tested the Function using an alert('').
The alert is working fine, but as I replaced the alert with app.quit(); It didn't work anymore.
app.on('ready', function(){
//Create new window
mainWindow = new BrowserWindow({});
//Load html into window
mainWindow.loadURL(url.format({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file',
slashes: true
}));
//Build Menu from MenuTemplate
const mainMenu = Menu.buildFromTemplate(mainMenuTemplate);
//Insert Menu
Menu.setApplicationMenu(mainMenu);
});
function quitApplication(){
alert('This Button is Working');
}
I don't know what I made wrong, but I appreciate every help I could get.

Remove quitApplication() from the main Electron JS and add this in your main.js :
const electron = require('electron');
const remote = electron.remote;
function quitApplication(){
if (process.platform !== 'darwin') { remote.app.exit(); }
}
Another way, if you want to keep this code in the main Electon JS file, is to use IPC : https://electronjs.org/docs/api/ipc-main . The renderer can call a method in the main process which quits.

Related

How to enable the functionality of "linking files & images in my online web editor"?

I made my online web editor by watching a YouTube tutorial. It is working pretty fine & I did a fine job by adding my personal flavor to it, mainly by altering the CSS code. When I tried to link my external CSS file & an image to it than those tags aren't working, I'm not able to add an external file. Yes, those files are in same location/directory.
Does code mirror library can solve it? I tried that but it's not working.
my JavaScript code...
// Creating Dragging functionality
const left=document.querySelector(".left"),
right=document.querySelector(".right"),
bar=document.querySelector(".bar"),
editor=document.querySelector(".editor"),
run=document.querySelector(".btn-run"),
iframe=document.querySelector(".iframe"),
darkMode=document.querySelector(".btn-dark"),
lightMode=document.querySelector(".btn-light");
const drag=(e)=>{
e.preventDefault();
document.selection ? document.selection.empty() : window.getSelection().removeAllRanges();
left.style.width=(e.pageX-bar.offsetWidth/3)+"px";
editor.resize();
}
bar.addEventListener("mousedown", ()=>{
document.addEventListener("mousemove", drag);
})
bar.addEventListener("mouseup", ()=>{
document.removeEventListener("mousemove", drag);
})
// Run Btn event listner
run.addEventListener("click", ()=>{
const html=editor.textContent;
iframe.src="data:text/html;charset=utf-8," + encodeURI(html);
})
// setting dark mode
darkMode.addEventListener("click", ()=>{
editor.style.backgroundColor="#282A35"
editor.style.color="white"
})
// setting light mode
lightMode.addEventListener("click", ()=>{
editor.style.backgroundColor="white"
editor.style.color="black"
})
// live code
document.getElementById("live").onclick=function(){
if (this.checked){
editor.addEventListener("keyup", ()=>{
const html=editor.textContent;
iframe.src="data:text/html;charset=utf-8," + encodeURI(html);
})
}
}
For local directories:
One solution could be using the full directory path in the src for the image and the href for the CSS to see if you get an established link.
If you're using abbreviated links and testing from a local directory, make sure that you're not putting a / in the wrong place in the abbreviated link in the src or href.
If you're attempting to link the files for your site and they're all in the same directory, make sure that there are no / at all in the front of the path.
IE: linking image.png and style.css in the same directory together as the HTML file would look like this:
<link rel="stylesheet" href="style.css"> and
<img src="image.png">
If they are in a child directory from the HTML it would look like this:
<link rel="stylesheet" href="child/style.css"> and
<img src="child/image.png">
Something as simple as this would break the link:
<link rel="stylesheet" href="/child/style.css"> and
<img src="/child/image.png">
|| OR this:
<link rel="stylesheet" href="/style.css"> and
<img src="/image.png">

Newby: index.js file doesn't work in index.html file

I'm new in Javascript world, currently I'm trying to implement a GUI using electron js framework.
Trying to reproduce the code from a tutorial, I got stuck on a code which seems not to work on my PC, basically even if I click on a button, the console is not logging anything (when it should have!!); the aim of the code is to refer to a button defined in an index.html file from a index.js containing the script and log a sentence when the button is clicked, but it seems like the script in the html file cannot access the .js file at all. Here I'm reporting the code from index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>my-app</title>
<link rel = "stylesheet" href="styles.css">
</head>
<body>
<button id = "button1" > START </button>
<script>
require('./index.js');
</script>
</body>
</html>
Here the code belonging to index.js file:
const electron = require("electron");
const button1 = document.getElementById("button1");
button1.addEventListener("click", startApp);
function startApp(){
console.log("Button clicked!");
};
Note:
I've tried to debug this code based on my very little knowledge of Javascript and electron:
I used document.getElementById("button1"); in index.html and it does work (the variable obtained was used to change button text color), but the same is not working when reported in the index.js file;
I tried console.log("In index.js"); in index.js but still it is not working!
From these results I thought the problem may be the .html and .js file communication; they are in the same folder. One more thing: I downloaded the tutorial code from GitHub and the problem is still present with the same actions at points 1 and 2.
Edit: I've omitted that I'm linking index.html window and displaying it in the main.js file, in fact the windows does show up, but the the click on the button doesn't produce any action.
Seemed to be a problem with the require module not working in .html file.
Solved by replacing it with <script src="index.js"></script>.
It appears that you shoud be using electron to load the index.html via BrowserWindowonce it is ready. app and BrowserWindow are from the electron module.
`const { app, BrowserWindow } = require('electron')`
function createWindow () {
const win = new BrowserWindow({
width: 800,
height: 600
})
win.loadFile('index.html')
}
app.whenReady().then(() => {
createWindow()
})
From the quick start
In Electron, browser windows can only be created after the app module's ready event is fired. You can wait for this event by using the app.whenReady() API. Call createWindow() after whenReady() resolves its Promise.
For futher info see https://www.electronjs.org/docs/tutorial/quick-start
Hope this proves useful.

Node.js and PowerShell Commands/Scripts

Here is the folder structure for my node.js project:
MySampleApp\
MySampleApp\Package.json
MySampleApp\Server.js
MySampleApp\public:
index.html - Invoked when server.js starts and shows "Click Me" button
fetchprocess.js - check button click and then show in DocumentElementID
user1.ps1 - runs Get-Process command to fetch processes
fetchprocess.js:
console.log('Client-side code running');
const button = document.getElementById('myButton');
button.addEventListener('click', function(e) {
console.log('button was clicked');
document.getElementById('counter').innerHTML = "ClickedNow";
var ps = new shell({
executionPolicy: 'bypass',
noProfile: true
});
app.get("/", function (req, res) {
ps.addCommand("./user.ps1", [ {
name: 'guid', value: req.params.guid
} ])
ps.invoke().then(output => {
res.end(output); // This is to show the output in web browser
})
})
});
Index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Example</title>
</head>
<body>
<p id="counter">Loading button click data.</p>
<button id="myButton">Click me!</button>
</body>
<script src="fetchprocess.js"></script>
</html>
My objective is to execute "user1.ps1" when someone clicks on the "ClickMe" button and then show the data in HTML Div (Counter). When I try to run above code it throws an error that require is not defined in fetchprocess.js file.
Image:
I will have several scripts under the public folder that will be executed when someone clicks on other buttons on the web app. What is the best folder structure for such project.
Thank you very much
TL; DR; There is no way you can execute Node.js code in a browser.
Looks like you messaged up with libraries. You are trying to execute some Node.js code in the browser.
<script src="fetchprocess.js"></script>
Here you are loading the script in the browser. The truth is that Browser JS code does not have access to the platform things like PowerShell and it is not Node.js at all. If you need to execute Node.js code use Node.js executable.
UPD:
The workaround may be the following.
Spin up HTTP server locally with Node.js
Add an endpoint that runs the PS script once it receives a request.
On-click send AJAX request to your server.
But it worth noticing that it will work only on the machine where the Node.js server is running. Because it is not possible to run PowerShell from a browser.

My HTML file won't link with my Javascript file

I am trying to complete an exercise for one of my courses and my HTML file won't link with my Javascript file. I put the link between my HTML file and my Javascript file in the body of my HTML file but the files still won't connect. When I test this code in Microsoft Edge, the buttons simply do not work. Anybody know what the problem is?
HTML
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>HTML Page</title>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
</head>
<body>
<button onclick = "startWorker()">Start Worker</button>
<button onclick = "stopWorker()">Stop Worker</button>
<ul id = "output">
</ul>
<script type = "text/javascript" src = "/js/script.js"></script>
</body>
</html>
Javascript
var worker;
function startWorker(){
worker = new Worker ("js/mod4_worker.js");
worker.onmessage = function(event){
document.getElementById("output").innerHTML += '<li>' + event.data + '</li>';
};
}
function stopWorker(){
worker.terminate();
}
Files
So, I would try my comments :
Change the script.js path to : "../js/script.js"
Change the worker passed script to "../js/mod4_worker.js"
As GGG said, using a path starting with "/", a slash, use the path from root. The full path is either :
Windows : file://DriveLetter:\REST_OF_PATH
Unix/Linux/OSX : file:///REST_OF_PATH
WebServer : http://domain/REST_OF_PATH
If the structure is from /webapp/ :
html/index.html
js/script.js
Accessing script.js from index.html needs to go back one folder (..) and then set the path seen here (js/script.js) which gives (../js/script.js) OR using full path (/webapp/js/script.js) which I wouldn't recommend because if you change "webapp" directory of location or URL (on WebServer)
Remove the / from your src in the index.html. So it should be
src = "js/script.js"
Why? When you begin the src value with a /, that means you're referring to an absolute path (in other words, it starts the path from your drive's root). My devtools shows it as
file:///C:/js/script.js
By removing the first / in your src, you're now doing relative pathing, and it will look in the correct place.
Permissions & File locations
(Stumbled on this Q and here's the only way I solved it...)
For me, I found it was a permissions and file location issue...
I'm running a local webserver on Ubuntu 18 Desktop, working with dev from a local folder linked to the web directory: /var/www/html/MY_DEV -> /home/me/MY_DEV. So, the www-data user couldn't actually "own" them like it needed to.
I use this setup just fine for PHP, HTML, and CSS just fine. But, if I include a javascript file via src="", no matter what I do, it doesn't work.
The only way I could get it to work on my desktop is if BOTH the served file (somefile.php or somefile.html) are physically at /var/www/html/...
And, of course accessing them at localhost/...
And, of course owning them obsessively with sudo chown -R www-data:www-data /var/www/html

Meteor iron-router splash screen error on deploy only

I'm using Meteor 1.0.3.1 on my local machine, and I'm deploying with node v0.10.36. However, the deploy machine only ever displays the iron-router splash screen... "iron:router" "Organize your Meteor application" ...
There are several other stacks about fixing this exact problem, including removing the tag and removing the projects npm.js file (left over from bootstrap). None of these are working.
project.js file is as follows:
Router.route('/', function () {
this.render('home');
});
Router.route('/about', function () {
this.render('about');
});
Router.route('/contact', function () {
this.render('contact');
});
Router.route('/legal', function () {
this.render('legal');
});
Router.route('imitationgamereview', function () {
this.render('imitationgamereview');
});
if (Meteor.isClient) {
}
if (Meteor.isServer) {
Meteor.startup(function () {
// code to run on server at startup
});
}
project.html file is as follows:
<head>
<title>my sample project</title>
<link rel="shortcut icon" href="/favicon.ico?v=2" />
</head>
<template name="home">
test
</template>
Totally going bonkers! WTF iron-router? I'm so in love with you, then you do stuff to me like this!
Perhaps it has to do with the file location of your routing file (project.js). Moving the it to /lib solved the problem for me.
I was getting the same splash screen on x.meteor.com and --production emulation until i made sure that every
Meteor.publish({});
is in an if(Meteor.isServer) statement e.g.
if(Meteor.isServer) {
Meteor.publish('files', function() {
return Files.find();
});
}
This fixed the problem for me.
I've just had a similar problem, and i don't know if this applies to you, but in my case it was the fact that i had two templates (two HTML files) with the same template name. Once i removed one of them, all came back to normal.
I.e., i had this line in both file1.html and file2.html :
<template name="sampleList">
Nothing really indicated where the problem lied.

Categories