How to stop page from auto refreshing with JavaScript? - javascript

I am quite new to web dev and currently, I work on a JS course. I have a problem with the automatic page refreshing that happens in Chrome and Safari also.
I have read that this refreshing can be caused by input submission in HTML but this problem occurs even when I do not use any type of button. In the code below, I tried to make a counter of the best score of all games when I guess the numbers, but I cannot record this score because my browser randomly refreshes my localhost and therefore all data is lost. As I said this problem occurs even when I do not use any type of submitting in my code (page randomly refreshes itself).
I have tried to disable adblocker in my browsers, but this did not help. Also, I tried to use window.stop() at the start and end of the code, but this did not seem desirable because safari always showed that it is still loading the page. Also, I have read that this can be caused by some sort of RAM optimization in the browser and therefore I tried to execute the code with only one tab open but this did not help either. I use Live Server extension with VS Code and therefore I do not run live server with node.js through terminal.
Because this problem occurs in multiple browsers I figured that it can be solved by some additional code in JS for example. Do you have any idea how could I solve this problem? I have run out of ideas at this point.
My Code:
"use strict";
let secretNumber = Math.trunc(Math.random() * 20) + 1;
let score = 20;
let highScore = 0;
document.querySelector(".check").addEventListener("click", function() {
const guess = Number(document.querySelector(".guess").value);
if (!guess) {
// When there is no input
document.querySelector(".message").textContent = "No Number";
} else if (secretNumber === guess) {
// When correct guess
document.querySelector(".number").textContent = secretNumber;
document.querySelector(".message").textContent = "Correct guess! πŸŽ‰";
document.querySelector("body").style.backgroundColor = "#228B22";
if (score > highScore) {
highScore = score;
document.querySelector(".highscore").textContent = highScore;
}
} else if (secretNumber < guess) {
// When guess is too high
if (score > 1) {
score--;
document.querySelector(".score").textContent = score;
document.querySelector(".message").textContent = "Too High";
} else {
document.querySelector(".score").textContent = 0;
document.querySelector(".message").textContent = "You lost the game.";
}
} else {
// When guess is too low
if (score > 1) {
score--;
document.querySelector(".score").textContent = score;
document.querySelector(".message").textContent = "Too Low";
} else {
document.querySelector(".score").textContent = 0;
document.querySelector(".message").textContent = "You lost the game.";
}
}
// Reseting Game With Button
document.querySelector(".again").addEventListener("click", function() {
score = 20;
document.querySelector(".score").textContent = score;
secretNumber = Math.trunc(Math.random() * 20) + 1;
document.querySelector(".message").textContent = "Start Guessing";
document.querySelector(".number").textContent = "?";
document.querySelector("body").style.backgroundColor = "#222222";
document.querySelector(".guess").value = "";
});
});
<!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" />
<link rel="stylesheet" href="style.css" />
<title>Guess My Number!</title>
</head>
<body>
<header>
<h1>Guess My Number!</h1>
<p class="between">(Between 1 and 20)</p>
<button class="btn again">Again!</button>
<div class="number">?</div>
</header>
<main>
<section class="left">
<input type="number" class="guess" />
<button class="btn check">Check!</button>
</section>
<section class="right">
<p class="message">Start guessing...</p>
<p class="label-score">πŸ’― Score: <span class="score">20</span></p>
<p class="label-highscore">
πŸ₯‡ Highscore: <span class="highscore">0</span>
</p>
</section>
</main>
<script src="script.js"></script>
</body>
</html>
Currently, I use this Chrome version "Version 92.0.4515.159 (Official Build) (arm64)" and this Safari version "Version 14.1.2 (16611.3.10.1.3)" with MacBook Air(2020) with M1 chip and 16 GB of RAM.

I use Live Server extension with VS Code…
This extension is designed to refresh your browser every time your file is changed (in some cases using the file buffer in VSCode). Disable the extension if you don't want this behavior.

Apparently, there is a problem with refreshing browser windows with localhost when loading code from external SSD. I disabled the Live Server extension in VS Code and installed node.js and run the live server from there but this did not help either. When I moved my files from the external SSD into the machine everything worked correctly.

Related

redundant command line of javascript program?

I am newbie with javascript and I wrote a very simple program to display something using function and alert. Here is my code
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<script>
var balance = 10500;
var cameraOn = true;
function steal(balance, amount){
cameraOn = false;
if (amount < balance) {
balance = balance - amount;
}
return amount;
cameraOn = true;
}
var amount = steal(balance, 1250);
alert("Criminal: you stole " + amount + "!");
</script>
</body>
</html>
The code is ok, when I ran it, it display "Criminal: you stole 1250!" as I expected. But, my problem is, in my code as you can see, there is a code cameraOn = true; I do not know why I must write this code ( I copy this code from the book I studied ).
When I made this line to be referenced, the result did not change. So, I thought that this code is not necessary ?
Could you please give me some ideas for me with this problem ? Thank you very much.
It's not executed since it's written after the "return" keyword.
So yes, you can (you should) delete this line.

How do I access a text to speech voice when I make a website ( for Edge browser)

When I run load the webpage below in Edge it tells me that 8 voices are available on my computer. But only 2 are operational voice[4] and voice[7]. In firefox there is only one available and operational, voice[0].
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width">
<title>Speech synthesiser</title>
<script>
var synth = window.speechSynthesis;
function populateVoiceList() {
var voiceSelect = document.getElementById("voicesAvailable");
voiceSelect.innerHTML = '';
voices = synth.getVoices();
for(i = 0; i < voices.length ; i++) {
var option = document.createElement('option');
option.textContent = voices[i].name + ' (' + voices[i].lang + ')';
voiceSelect.appendChild(option);
}
}
</script>
</head>
<body onload="populateVoiceList()">
<h1>speech test 1</h1>
<form id="myForm">
<select id="voicesAvailable">
<option>Choose a voice</option>
</select>
</form>
</body>
</html>
In Microsoft Edge browser there seems to be a geographic filter being applied to restrict the voices. So, while 8 names get placed in the drop-down box only 2 actually are available. How do I modify the program so that I only load the voices which will work on the computer?
Any advice appreciated.
Thanks
New Edit..
I found a related question containing a response from Islam Elshobokosy. He submitted this code snippet:
speechSynthesis.onvoiceschanged = function() {
var voices = this.getVoices();
console.log(voices);
};
When I clicked the associated button on the Stack Overflow page to run that code it produced a result that revealed the only two functioning voices on my computer. It did not give the other 6.
My question is now:
1. How is this code filtering out the 6 irrelevant voices that my webpage page (above) is finding?
2. How do I incorporate something like this into my webpage?

Error while fetching elements of an IFrame inside HTA

We are trying to acheive automation of an Intranet site. We are using HTA along with java script for this purpose. Instead of opening the site in browser, we are using an Iframe, withing the HTA itself, for it (Since the browser security settings bars us from doing anything). Eare able to login to the website,however, after every step from then we get this error message, saying "Unable to get property 'children' of undefined or null reference."
below this it also gives a URL : http://*******..*:8888/cs/domainname/cache/PT_HNAV_JS_MIN_1.js
To be more specific, it is a peoplesoft site. Can someone shed light on how to resolve this ?
Below is the HTML code :
<html>
<head>
<HTA:APPLICATION
APPLICATIONNAME="HTA"
SYSMENU="YES"
>
<meta http-equiv="x-ua-compatible" content="ie=9">
<title>HTA</title>
<script type="text/javascript">
function Start() {
var iframePage = document.getElementById('iframeid').contentDocument;
var userId = iframePage.getElementById("userid");
var passwd = iframePage.getElementById("pwd");
var form = iframePage.getElementById("login");
userId.value='##';
passwd.value='##';
form.submit();
}
</script>
</head>
<body>
<form class="form" name="form">
<input class="links" type="button" value="Project Plan" onclick="Start();" />
</form>
<iframe application="no" src="http://****.**.****:8888/psp/sitename/?cmd=login&languageCd=ENG&" width="600" height="600" id="iframeid">
</body>
</html>
I could find the first occurance of children in the relevant js file is below :
this.fakeBCReqWC = false;
var bchidden = 0;
if(eBC.childNodes.length == 0) bchidden=1;
this.bcScrollUl = ptUtil.id(pthNav.bcScrollId);
if (eBC.children[1])
var clickedURL = eBC.children[1].firstChild.href;
var nChildren = 0;
if (this.bcScrollUl)
nChildren = this.bcScrollUl.children.length;
var nIdx = 0;
if (this.fakeBCSetN) {
var isBCpath = false;
var fakechildindex = 0;
var i = 0;
while(nIdx < nChildren) {
var child = this.bcScrollUl.children[nIdx];
if(child.id && child.id.indexOf ("FAKE") != -1 && child.firstChild && child.firstChild.href == clickedURL) {
isBCpath = true; fakechildindex = nIdx; break; }
nIdx++; }
Changing x-ua-compatible to point to IE 11 resolved the issue. Earlier it pointed to IE9.
not sure why you did application="no"
you should do application="yes" to enable the iframe and parent hta window to communicate and allow your hta to work with the iframe dom.
however, that is from my experience with HTAs while working with IE6/7 and that was a long time ago
see more at msdn:
https://msdn.microsoft.com/en-us/library/ms536496(v=vs.85).aspx#Security

Program will not load Failed to load resource: the server responded with a status of 404 (Not Found)

I am trying to create a code that will determine your school grade by entering your university credits and will output the student name and grade. However I am getting an error I have never seen before. I am new to this and can't seem to debugg it. Thanks in advance!
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="utf-8">
<title>University Credits</title>
<script type="text/javascript">
/* Input Name and Credits from user.
* Process the studnets number of university credits.
* Outputs the student's Name and School year.
*/
function credits() {
//Get name and univesity credits from user.
var studentName = document.getElementById("nameBox").value;
var creditNumber = parseFloat(document.getElementById("creditBox").value);
/*Compute number of credits to determine school grade.
If the number of credits is And the number of credits Then the year in school is:
greater than or equal to: is less than:
0 30 freshman
30 60 sophomore
60 90 junior
90 ∞ senior
*/
var credits;
if (creditNumber >= 0 || creditNumber < 30){
credits="freshman"
}else if (creditNumber >= 30 || creditNumber < 60){
credits="sophomore"
}else if (creditNumber >= 60 || creditNumber < 90){
credits="sophomore"
}else if (creditNumber >= 90 || creditNumber < number.MAX_VALUE){
credits="sophomore"
}
//Display nameand grade to user.
var nameCredit= studentName + creditNumber;
document.getElementById("nameGrade").innerHTML = nameCredit;
}
</script>
</head>
<body>
<h1>Enter you Name and University Credits to determinet your school grade.</h1>
Name: <input type= "text" id= "nameBox" size=3>
University Credits: <input type="text" id= "creditBox" size=3>
<button type="button" onlick="credits()">School Grade </button>
</body>
</html>
The 404 error has nothing to do with your code. The error is because your browser is not finding a favicon. Browsers look for favicon.ico in the root directory of your web server; it is the icon that appears on the browser tab for the page or by a bookmark, shortcut, etc. If you don't have a favicon.ico file on your server (in this case the one you are running on your local machine) you will get a 404 error for it. Not having one doesn't hurt anything, it just means browsers might complain when they don't find it.
It appears that your code is not attempting to run because of a typo. Instead of attaching an event handler to the click event you are attaching it to the non-existent lick event:
<button type="button" onlick="credits()">School Grade</button>
Also the code you posted won't display any output, the DOM doesn't contain a nameGrade element to output to.

Cross-browser alternative of Date.now() and innerHTML security?

I have PHP form validation rules working but I also don't want valid but nonsense real human-being spams. Currently, the JavaScript code below gets the timestamp of the page loaded time and the timestamp of the form submission. If the difference is below 18 seconds it asks 'are you superman?' in an alert box and doesn't allow the user to submit until time arrives.
Q1 ) Date.now() is supported by ie9+. Which alternative function achieves the same work in ie7+ ? (reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now#Browser_compatibility)
Q2 ) Does this function itself has security gap? I ask because I suspect of document.getElementById('PageLoadTime').innerHTML = pageloaded code if variable pageloaded could be edited from outside!
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>trial</title>
</head>
<body>
<div>user page loading timestamp: <span id="PageLoadTime"></span></div>
<div>form submission timestamp: <span id="submitTime"></span></div>
<div>time difference: <span id="difference"></span></div>
<script>
var pageloaded = Date.now();
document.getElementById('PageLoadTime').innerHTML = pageloaded;
function GetSubmitTime(pageloaded) {
document.getElementById('submitTime').innerHTML = Date.now();
document.getElementById('difference').innerHTML = Math.floor((Date.now() - pageloaded)/1000);
if ( Math.floor((Date.now() - pageloaded)/1000) < 18 )
{
if(event.preventDefault){
event.preventDefault();
}else{
event.returnValue = false; // for IE as dont support preventDefault;
}
alert("are you superman?");
}
}
</script>
<form method="post" action="my home page" onsubmit="GetSubmitTime(pageloaded)">
<input type="text" id="e1" name="n1">
<input type="submit" value="send" >
</form>
</body>
</html>
Date.now() returns what new Date().getTime() returns, and the latter has been supported essentially forever.
Setting the innerHTML of an element to a system timestamp is not a security risk.
Nothing in the client is safe from user tampering. Anybody using your form can force the form to be submitted without any regard to your time check.
Answer to your first question. Put the following at the top of your JavaScript and you can use Date.now() even on IE < IE9.
Date.now = Date.now || function() { return +new Date; };
console.log(Date.now()); // 1406206659562
Furthermore, your code in general is fine, though the security on the client side is always relative.

Categories

Resources