Uncaught ReferenceError: require is not defined at add.js:1 - javascript

I am trying to get set up on a simple Electron project, but am having trouble resolving this issue. I have a file add.js that is used to add an event listener to a button to close a frameless browser window. I have the add.js file imported in a script tag to the HTML like so:
<script src="add.js"></script>
The add.js file only contains this event listener:
const electron = require('electron')
const remote = electron.remote
const closeBtn = document.getElementById('closeBtn')
closeBtn.addEventListener('click', (event) => {
let window = remote.getCurrentWindow();
window.close();
})
If it is needed, here is index.js, the click event listener to open this window:
const electron = require('electron');
const path = require('path');
const BrowserWindow = electron.remote.BrowserWindow;
const notifyBtn = document.getElementById('notifyBtn');
notifyBtn.addEventListener('click', (event) => {
const modalPath = path.join('file://', __dirname, 'add.html')
let win = new BrowserWindow({
alwaysOnTop: true,
frame: false,
transparent: true,
width: 400,
height: 200
})
win.loadURL(modalPath)
win.show()
win.webContents.openDevTools();
win.on('close', () => win = null)
})
The problem that I am having is that the frameless browser window opens just fine, but I get the "Uncaught ReferenceError:" immediately and the JS code does not load.
I've tried looking up the issue on here (stackoverflow) but the answers suggest that this is caused by attempting to run a node program in the browser. However, the index.js code that I included above works just fine, with no errors.
Here is the code to the HTML files as well, just in case I'm going crazy:
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>BTCAlert</title>
<link rel="stylesheet" href="../assets/css/main.css">
</head>
<body>
<div class="row">
<div id="price-container">
<p class="subtext">Current BTC USD</p>
<h1 id="price">Loading..</h1>
</div>
<div id="goal-container">
<p><img src="../assets/images/up.svg"><span id="targetPrice">Choose a Target Price</span></p>
</div>
<div id="right-container">
<button id="notifyBtn">Notify Me When...</button>
</div>
</div>
<script src="index.js"></script>
</body>
</html>
add.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" href="../assets/css/main.css">
<link rel="stylesheet" href="../assets/css/add.css">
</head>
<body>
<p class="notify">Notify me when BTC reaches..</p>
<div class="row2">
<div>
<input id="notifyVal" placeholder="USD">
</div>
<button id="updateBtn">Update</button>
</div>
<a id="closeBtn">Close Window</a><br>
</div>
<script src="add.js"></script>
</body>
</html>
Any help is greatly appreciated.

Adding
webPreferences: {
nodeIntegration: true
},
to the new BrowserWindow instance fixed this issue for me.

The require() function it can not be used in the client side....
Anywhere if u want to use it in client side you should look into require.js or head.js for this.

Related

why is this appearing ?: clone.getElementById is not a function

I've got this error:
index.js:29 Uncaught TypeError: clone.getElementById is not a function
at HTMLButtonElement.changeImg (index.js:29:11)
changeImg # index.js:29
It marks the line highlighted. I don't understand why. If somebody can help me I'll appreciate it.
//captura de elementos:
const btn = document.querySelector('.btn');
const templateImg = document.querySelector('.templateImg').content;
const imgContainer = document.querySelector('.imgContainer');
const fragment = document.createDocumentFragment();
let arrayImg = [
"/img/food1.jpg",
"/img/food2.jpg",
"/img/food3.jpg",
"/img/food4.jpg",
"/img/food5.jpg",
"/img/food6.jpg",
"/img/food7.jpg",
"/img/food8.jpg",
"/img/food9.jpg"
];
const changeImg = () => {
let ran = Math.floor(Math.random() * 9);
//Crear clon del template:
const clone = templateImg.firstElementChild.cloneNode(true);
console.log(clone);
console.log(arrayImg[ran]);
//capturar elemento y modificar el src:
clone.getElementById("img").src = arrayImg[ran];
fragment.appendChild(clone);
imgContainer.appendChild(fragment);
}
btn.addEventListener('click', changeImg);
<!DOCTYPE html>
<html lang="es">
<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">
<link rel="StyleSheet" href= "style.css" type= "text/css">
<title>Cambiador de imagenes</title>
</head>
<body>
<div class="container">
h1>Food and drink in Florianopolis</h1>
<div class="imgContainer"><!--templateImg--></div>
<button type="text" class="btn" id="btn">Change</button>
</div>
<template class="templateImg">
<img id="img" src="/img/food1.jpg">
</template>
<script src="./index.js"></script>
</body>
</html>
I was trying to change the images inside the template modifying the src:
<template class="templateImg">
<img id="img" src="/img/food1.jpg">
</template>
When I use querySelector, the error is that the value I try to replace is null even though it's not, and with getElementById, I get that message that it's not a function.
you create a "clone" with this code:
const clone = templateImg.firstElementChild.cloneNode(true);
that is a image element(see in console) and you for changing image src just need to use this code:
clone.src = arrayImg[ran];
getElementById() is a method of document not of any HTML element.
What you want to use instead is querySelector which you can in fact use on elements.

How do I update the input value using an onchange event and get the value in vanilla Javascript?

I am doing an assignment where I make a simple API call using fetch to retrieve an image a of dog by breed. The one issue I can't resolve is that the input value never changes when I try to retrieve an image of a different breed. the default value, which is 'hound', reappears after I press submit. I know I need to attach an onchange event to my input but I am not sure how to write it or how to get the value after the onchange event is triggered. Any help would be greatly appreciated. I originally wrote this with jQuery but decided to rewrite it in vanilla Javascript so that's why there is no jQuery.
I put a '<---' on the line I am struggling with.
P.S I know my code isn't very good, I am new to this.
Javascript
function getJson(breed) {
fetch("https://dog.ceo/api/breed/" + breed + "/images/random")
.then((response) => response.json())
.then((responseJson) => displayResults(responseJson));
}
function displayResults(responseJson) {
const dogImage = responseJson.message;
let breedImage = "";
let container = document.createElement("div");
console.log(dogImage);
breedImage += `<img src="${dogImage}">`;
container.innerHTML = breedImage;
document.querySelector(".results-img").innerHTML = "";
document.querySelector(".results-img").appendChild(container);
}
function submitButton() {
let breedName = document.querySelector("#numberValue").value;
breedName.addEventListener().onchange.value; <---
document.getElementById("dog-input").addEventListener("submit", (e) => {
e.preventDefault();
getJson(breedName);
});
}
submitButton();
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Dog Api</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="container">
<form>
<input id="numberValue" type="text" value="hound" />
<button type="submit" class="submit-button">Submit</button>
</form>
<section class="results">
<h2>Look at these Dogs!</h2>
<div class="results-img"></div>
</section>
</div>
<script src="main.js"></script>
</body>
</html>
You don't need an onchange event handler. Currently you're storing the value of the input in breedName when you call submitButton. That means that breedName will never change because it is merely a reference to the value at that moment.
Instead create a reference to the element and read the value property in the submit event handler. That will get the value how it is at the time you submit.
function getJson(breedName) {
console.log(breedName);
}
function submitButton() {
const form = document.querySelector('#dog-form');
const input = document.querySelector('#numberValue');
form.addEventListener('submit', event => {
event.preventDefault();
const breedName = input.value;
getJson(breedName);
});
}
submitButton()
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Dog Api</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="container">
<form id="dog-form">
<input id="numberValue" type="text" value="hound" />
<button type="submit" class="submit-button">Submit</button>
</form>
<section class="results">
<h2>Look at these Dogs!</h2>
<div class="results-img"></div>
</section>
</div>
<script src="main.js"></script>
</body>
</html>

Electron modal javascript button not working

I am learning to create apps using electron. So far I have a main.js file running on the main process, and then I have an index.js for my index.html page, and I have a modal popup add.html which uses an add.js file. I have 2 buttons in my add.html file and I can't get either of them to work no matter what method I use. I have tried using the following methods to use the button:
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Add Room</title>
<!-- <link rel="stylesheet" href="../assets/css/main.css"> -->
<link rel="stylesheet" href="../assets/css/add.css">
</head>
<body>
<!-- <p class="name">Address: </p> -->
<div class="row">
<div class="address">
<input class="nameVal" placeholder="Address">
</div>
<div>
<button class="add"> Add </button>
<button id="cancelBtn" class="cancel" onclick="cancelButton">Cancel</button>
</div>
</div>
<!-- <a id="close">Close</a> -->
<script src="./add.js"></script>
</body>
</html>
Javascript:
const electron = require('electron');
const path = require('path');
const BrowserWindow = electron.remote.BrowserWindow;
const currWindow = electron.remote.getCurrentWindow();
const ipc = require('electron').ipcRenderer;
let cancelBtn = document.getElementById('cancelBtn');
var $ = document.querySelectorAll.bind(document);
//This method is used in index.js and it works perfectly.
$(".cancel").forEach(function (el) {
el.addEventListener("click", function() {
alert("this thing is doinh stuuffff");
});
});
cancelBtn.addEventListener("click", function() {
alert("this thing is doing stufff");
});
function cancelButton() {
alert("this thing is using the onclick property");
}
I know that my html is linking to my javascript because if I make the javascript popup an alert without using a button it works.
I have seen other posts with a similar problem, but their issue was fixed because they had a typo. I re-wrote and re-read my code multiple times over the course of a few days, so I doubt that the issue is due to a typo.
add.html is used as a modal window, so maybe there are some rules that I'm missing about modal windows? But its called from main.js using icp and it works fine:
ipc.on('open-add-room-window', () => {
var addRoom = new BrowserWindow({parent: win, modal: true, width: 300, height: 150, resizable: false, show: false});
addRoom.loadFile("src/add.html");
addRoom.on('close', () => { addRoom = null; });
addRoom.once('ready-to-show', () => {
addRoom.show();
});
});
Thanks to #tpikachu I was able to solve the issue by enabling nodeIntegration on my modal BrowserWindow using the following code:
var addRoom = new BrowserWindow({webPreferences: {nodeIntegration: true}, parent: win, modal: true, width: 300, height: 150, resizable: false, show: false});

Input fields dead after clearing them

In my electron app I have a function to clear my input fields on a button press, but after using it I can't click and type into inputs anymore. However, if I open up the inspector window, they work again.
Why does this happen and how do I fix it?
Electron app's main.js:
const { app, BrowserWindow, Menu } = require('electron');
let win;
function createWindow() {
win = new BrowserWindow();
win.loadFile('window_main/index.html');
}
app.on('ready', createWindow);
index.html
<body>
<input type="text" id="testinput" />
<button id="clear">Clear</button>
<script src="index.js" type="text/javascript"></script>
</body>
The problematic bit of JS in index.js:
document.getElementById('clear').addEventListener("click", clear);
function clear() {
if (confirm("Clear all inputs?")) {
document.querySelectorAll('input').forEach((input) => {
input.value = '';
})
}
}
I reproduced your code after removing the script which is not explained why you are using it, anyhow below is a code using jQuery does the trick, this should get you to the right place at least.. if still didn't work with you post a better explanation of your code for a better help...
mark it as answered if it solves your problem....
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<title>Document</title>
</head>
<body>
<input type="text" id="testinput" />
<button id="clear">Clear</button>
<script>
$(document).ready(()=>{
document.getElementById('clear').addEventListener("click", clear);
})
function clear() {
if (confirm("Clear all inputs?")) {
document.querySelectorAll('input').forEach((input) => {
$(input).val('');
})
}
}
</script>
</body>
</html>
The problem was not clearing the inputs, but rather showing the confirm box. I used the following snippet instead:
dialog.showMessageBoxSync(
title: "Clear inputs",
message: "Clear all input boxes?",
type: "warning",
buttons: ["Cancel", "Ok"]
})
And now everything works as expected.

Progress bar in Electron environment using BootstrapJS not working properly

Environment: Electron 1.6.11 (which includes NodeJS) and Bootstrap 3.3.x for the UI
Desired results:
I would like to:
Start a indeterminate progress bar when the Run button is clicked
Run a process (a Java program) -- which runs successfully
Remove the indeterminate progress bar when the process (Java program) returns
What I get in the following code is:
the process (Java program) starts
the process (Java program) ends
then the indeterminate progress bar appears
(I cannot remove it when trying -- see commented code)
Possibly, I am not synchronizing my processing correctly.
I thought the NodeJS code
resultCode = execSync(javaCmd);
would allow the page to wait for the Java program to complete.
I suspect that the code
var execSync = require('child_process').execSync;
is creating a child process in the background that does NOT wait even though I am using execSync.
Can you assist?
<!doctype html>
<html lang="en">
<head>
<script>
window.$ = window.jQuery =
require('./node_modules/jquery/dist/jquery.min.js');
</script>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0' name='viewport' />
<meta name="viewport" content="width=device-width" />
<link href="light-bootstrap-dashboard-master/assets/css/bootstrap.min.css" rel="stylesheet" />
<link href="light-bootstrap-dashboard-master/assets/css/animate.min.css" rel="stylesheet"/>
<style>
.progress {
margin: 15px;
}
.progress .progress-bar.active {
font-weight: 500;
animation: progress-bar-stripes 1.5s linear infinite;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="container">
<div class="form-check form-group">
<button type="submit" class="btn btn-success btn-fill" onclick='runJob()'>Run</button>
<br>
<br>
<div class="progress-bar progress-bar-striped active" id="bar" role="progressbar" style="width: 100%;">
<span>Processing</span>
</div>
</div>
</div>
</div>
<script language="javascript" type="text/javascript">
$(document).ready(function() {
document.getElementById('bar').style.display = 'none';
});
</script>
<script language='javascript' type="text/javascript">
function runJob() {
var execSync = require('child_process').execSync;
var javaCmd = 'java -jar C:/Java_Code/CountDown.jar';
alert("Run process?");
// make progress bar visible here but does not work in sequence with job
document.getElementById('bar').style.display = 'block';
var resultCode;
resultCode = execSync(javaCmd);
// would like to remove progress bar here but does not work
//document.getElementById('bar').style.display = 'none';
alert("Command succesfully executed");
}
</script>
</body>
<!-- Core JS Files -->
<script src="light-bootstrap-dashboard-master/assets/js/jquery-1.10.2.js" type="text/javascript"></script>
<script src="light-bootstrap-dashboard-master/assets/js/bootstrap.min.js" type="text/javascript"></script>
</html>

Categories