Electron HTML Javascript button not working - javascript

I'm trying to create and save files using javascript.
This is my HTML code:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Tutorial</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.con/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="./css/styles.css">
</head>
<body>
<div class="container" id="form-container">
<textarea class= "form-control" placeholder ="File Contents..." rows="10"></textarea>
<input id= "content" class="form-control" placeholder="Input Text Here...">
<button id="createButton" class="btn btn-success">Create File</button>
</div>
</body>
<script>
require('./renderer.js')
</script>
</html>
The page looks like this currently. For some reason I don't understand, the button to create file doesn't work I click it but nothing happens. It does not create a file, nor does it open a location where you want to save the file.
This is my Javascript code:
var app = require('electron').remote;
var dialog = app.dialog;
var fs = require('fs');
document.getElementbyId('createButton').onclick = () => {
dialog.showSaveDialog((fileName) => {
if(fileName === undefined){
alert("You didnt save the file");
return;
}
var content = document.getElementbyId('content').value;
fs.writeFile(FileName, content, (err) => {
if(err) console.log(err);
alert("The file has been succesfully saved")
})
});
};
Why won't the 'Create File' button work?

The function you are trying to use is called document.getElementById, using the camel-case naming convention. Your code would look like this, when corrected:
//... require statements as in your code
document.getElementById("createButton").onclick = () => {
// ...
var content = document.getElementById("content").value;
// ...
}

Related

Switch Github profile pictures according to the theme

I would like to automate the change of the profile picture according to the current theme on the github page, day or night. Is there a way to make this change?
I tried an html script but no way to get a result on github.
<!DOCTYPE html>
<html>
<head>
<title>switch_them</title>
</head>
<body>
<img id="day" src="img/0XCAF3_day.png" alt="day theme">
<img id="night" src="img/0XCAF3_night.png" alt="night theme">
<script>
function switchTheme() {
const dayThemePicture = '0XCAF3_day.png';
const nightThemePicture = '0XCAF3_night.png';
const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
if (mediaQuery.matches) {
document.getElementById('night').src = nightThemePicture;
} else {
document.getElementById('day').src = dayThemePicture;
}
}
switchTheme();
window.addEventListener('load', switchTheme);
window.addEventListener('resize', switchTheme);
</script>
</body>
</html>

How can I fetch data to display on a new HTML page after clicking a button on a main index.html page?

I have two html files (index.html and allUsers.html) and a JavaScript index.js
The index.html has a button allUsersButton.
My goal is that when the allUsersButton is clicked, I should see the allUsers.html page, and be able to see the fetched data which should be injected into the div named allUsersDivId.
So far, no data loads on the allUsers.html page and I get an error on the console "Uncaught TypeError: Cannot set properties of null (setting 'onclick')". Should both the index.html and the allUsers.html have the script linked in them? What's the best way to put this together?
index.html
<body>
<form action="http://localhost:7050/hello" method="POST">
<label for="username">User name:</label>
<input type="text" id="username" name="username"><br><br>
<input type="submit" value="Submit">
</form>
<button type="button" id="allUsersButton">All Users</button>
<script src="index.js"></script>
</body>
allUsers.html
<body>
<div id = "allUsersDivId">
</div>
<script src="index.js"></script>
</body>
index.js
Here I have a function for fetching and inserting the data into the div allUsersDivId which is in the allUsers.html, and an onClick listening on the allUsersButton which is in the index.html.
document.getElementById("allUsersButton").onclick = function() {displayAllUsers()};
function displayAllUsers() {
window.location.href='allUsers.html'
fetch("http://localhost:7050/allusers")
.then((response) => {
if (response.ok) {
return response.json();
} else {
throw new Error("NETWORK RESPONSE ERROR");
}
})
.then(data => {
for(var i = 0; i < data.length; i++){
const userName = data[i].username
const userNameDiv = document.getElementById("allUsersDivId")
const heading = document.createElement("h1")
heading.innerHTML = userName
userNameDiv.appendChild(heading)
}
})
.catch((error) => console.error("FETCH ERROR:", error));
}
What's the best way to link this all together?

Why can't I access javascript function from HTML file?

Fairly basic question here. I've run into a situation where I can't seem to access Javascript functions from within my HTML file, even though I've linked the JS file as a script src. It seems like a pretty simple issue but I can't figure out what the problem is.
I'm trying to add a function called startLogin to an HTML button. I added it as an onclick, but then when I try to click the button, the console says the function is undefined. However the function is clearly defined in the JS file and as far as I can tell the syntax I'm using for the onclick and the script src link is correct.
In addition I've confirmed that the JS file is linked to the HTML file. If I try to manipulate the DOM from the JS file just to do something simple, like set the background to red, that works fine. The problem is when I try to call a function defined in the JS file. Also I've made sure the function I'm trying to call does actually work. If I stick it right in the HTML file inside script tags, it works fine.
I've already tried moving the script tags inside the body at the end of the HTML, as I know that's often the issue, but in this case it didn't work. Can anyone help me identify why I'm unable to access the "startLogin" function from the HTML button?
FYI, this is a javascript project and I'm using Vite.js for bundling. All the other HTML/JS files in my project are playing nicely together, I'm only having an issue with the Login page.
file structure:
|-pages
|-login.html
|-login.js
login.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>Document</title>
<!-- LINK JS FILE -->
<!-- MODULE TYPE IS RELATED TO VITE.JS -->
<script type="module" src="./login.js"></script>
</head>
<body>
<!-- email login form -->
<form name="emailLogin" id="emailLogin" style="display: none">
<div class="row" style="width: 600px">
<div class="col">
<div class="form-row" style="padding-bottom: 10px">
<input
type="email"
class="form-control"
id="emailAddress"
placeholder="email associated with your login"
style="width: 576px"
/>
</div>
</div>
<div class="form-row">
<br />
<button type="button" class="btn btn-primary" onclick="startLogin('email')">
Send Email Login
</button>
</div>
</div>
</form>
</body>
</html>
login.js
// start the login process by generating a code sent either SMS or EMAIL
function startLogin(login_type) {
// local variables
var ajaxResult;
var subs;
var tempString;
// get the login values and set up the call
if (login_type == "phone") {
// get the values
use_country_code = $("#country").val();
use_phone = $("#phoneNumber").val();
use_phone = use_phone.replace(/\D/g, "");
// do the validation
if (use_phone.length < 10) {
$("#errorText").html(
"Phone number doesn't have enough digits, please try again."
);
$("#errorModal").modal("show");
return;
}
// build the url
post_url =
"https://us-central1-dev-api-327415.cloudfunctions.net/user-login?cc=" +
use_country_code +
"&phone=" +
use_phone;
} else {
// get the values
use_email = $("#emailAddress").val();
// do the validation
if (!validateEmail(use_email)) {
$("#errorText").html(
"Email address does not appear to be valid, please check the format and try again."
);
$("#errorModal").modal("show");
return;
}
// build the url
post_url =
"https://us-central1-dev-api-327415.cloudfunctions.net/user-login?email=" +
use_email;
}
// send the request to the server and process the results
$.LoadingOverlay("show");
$.ajax({
type: "POST",
url: post_url,
// process the returned result of the Ajax call
success: function (ajaxResult) {
// see if we have a session token and handle the response
session_token = ajaxResult["session_token"];
if (session_token == "None") {
// hide the login and show the text message area if phone, otherwise hide email and show email message
if (login_type == "phone") {
$("#loginMethod").hide();
$("#phoneLogin").hide();
$("#codeLogin").show();
$("#loginMessage").hide();
$("#textMessage").show();
} else {
$("#loginMethod").hide();
$("#emailLogin").hide();
$("#loginMessage").hide();
$("#codeLogin").show();
$("#emailMessage").show();
}
} else {
// hide everything since already logged in and show the right message
$("#phoneLogin").hide();
$("#emailLogin").hide();
$("#loginMethod").hide();
$("#loginMessage").hide();
$("#codeLogin").hide();
$("#continueLoginAlready").show();
}
},
// process after the Ajax call has been fully completed
complete: function () {
$.LoadingOverlay("hide");
},
// handle total failure
error: function (jqXHR, exception) {
console.log(jqXHR);
console.log(exception);
json_error = jqXHR["responseJSON"];
$("#errorText").html(json_error.error_message);
$("#errorModal").modal("show");
},
});
}
Javascript modules work a bit differently. There, variables and functions are not exposed to the global scope.
If you want to use your function from other parts of the code, you have to set it explicitly on the window object:
function startLogin(...) {
...
}
window.startLogin = startLogin;
an other solution is to set the js at end of the html, than you don't need to use the window object (memory lag)
<html lang="en">
<head>...</head>
<body>
<button type="button" id="myButton">Title</button>
</body>
<script>
function myFunction(){
console.log('running myFunction');
}
const button = document.querySelector('#myButton');
button.addEventListener('click', function clickListener(
{
myFunction();
}
</script>
</html>
the browser is simply stupid, it loads the page from top to bottom and if you load your js after the body all your html is present and you can do it this way.

How to add the current query string value in my page's hyperlinks?

My code goal is to search various websites at once.
I would like to do this while generating a query string with the search terms.(Mainly for analytics reasons). I use a form to do so.
With java-script I add the search term name to the array of links linkList.
Written from bits of code I found online, worked "fine" before adding the form part to generate my query string. Now it doesn't even display the links.
HTML
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="css/styles.css?v=1.0">
</head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="/scripts"></script>
<body>
<form id="test-form">
<div>
<input type="text" name="search" placeholder="Search"id="id"/>
<button type="submit" id="go">get links</button> </div> </form>
<div id="linkText"></div>
<div id="a">test</div>
</body>
</html>
Javascript
$(document).ready(function(){
//READ URL
let params = (new URL(document.location)).searchParams;
let name = params.get("search");
console.log(name)
//IF QUERY IN URL
if(name !== null && name !== '') {
// do something
}
else {
//ARRAY LIST 1
var linkList = {
"https://google.net":"Click",
"https://google.org=":"Click2",
};
//LINK GENERATION FROM ARRAY
for (link in linkList) {
if (linkList.hasOwnProperty(link)) {
var a = document.createElement('a'),
linkText = document.createTextNode(linkList[link]);
//ADD THE QUERY AT THE END OF THE LINK
a.href = link + name;
a.appendChild(linkText);
document.body.appendChild(a);
}
}
}
});
Found an easier solution that solved my problem :
I search the URL for the query parameters and call them name
let params = (new URL(document.location)).searchParams;
let name = params.get("search");
But I create the links in a less complicated manner
document.write('Link Name');
var foo = "http:example.com/search="+name;

How to display value from a Javascript function onto an HTML page?

index.js file
const {BrowserWindow, app, globalShortcut} = require('electron');
const url = require('url');
const si = require('systeminformation');
let win = null
function boot() {
//console.log(process.type)
win = new BrowserWindow({
width: 600,
height: 500,
frame: false
})
var output = document.getElementById("output");
output.innerHTML = "hello world"
//win.loadURL(file:'//${__dirname}/index.html')
win.loadURL('file://' + __dirname + '/index.html');
win.on('closed', () => {
win = null
})
}
app.on('ready', boot);
**index.html file **
<!DOCTYPE html>
<html lang= "en">
<head>
<meta charset="UTF-8">
<title>Hello World</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="content">
<header>
<div class="option" id="close">X</div>
<div class="option" id="minimize">-</div>
</header>
<div id="text">z</div>
<h1>
<p id="output"></p>
</h1>
</div>
<script src="./assets/js/script.js"></script>
</body>
</html>
So I am using the value from the following snippet to be display into my HTML page
var output = document.getElementById("output");
output.innerHTML = "hello world"
Through this on my HTML page:
<h1>
<p id="output"></p>
</h1>
But it gives me the error:
"reference error :document is not defined "
By the way I am creating an Electron app. Just trying to display some data from my javascript page to html page.
As per the code you provided, you are referring to the document before it gets loaded.
var output = document.getElementById("output"); // <- here and
output.innerHTML = "hello world";
win.loadURL('file://' + __dirname + '/index.html'); // <- here
Check if the DOM is ready before manipulating it.
The name of your JavaScript file is index.js. But you are including script.js file in the script tag. Change the script tag to specify path of index.js file:
<script src="./path_of_file/index.js"></script>

Categories

Resources