how can i protect my index.html website by js so i can only open it on my pc? - javascript

i want to make my local static html website password protected with some js, so that when i open my local html file in my pc, it comes with a form to fill up my user id and my own password, which i have saved and when i hit enter that should open my index.html file only when password is correct.
currently my code is
<!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>
</head>
<body>
<Form>
<!-- user-id -->
<input type="text">
<!-- user-password -->
<input type="password">
<button onclick="window.open('./index.html')"> Enter
</button>
</Form>
<script>
// pls-help-me-idk-how-to-code-js
</script>
</body>
</html> ``

Its not a proper way to do it. You need a backend for that inorder to properly execute that. But if it just to play around you can have an alert box and just compare their value : if right it displays.

First, you have to add an id or a class to that inputs in order to select them within the script section. Afterward, you can select them and add any value you want.
Such as:
<form>
<!-- user-id -->
<input id="user" type="text" />
<!-- user-password -->
<input id="pass" type="password" />
<button onclick="window.open('./index.html')">Enter</button>
</form>
<script>
document.getElementById("user").value = "UsernameOrId";
document.getElementById("pass").value = "SomePassword";
</script>
In order to compare, you should get the right password from somewhere like a database or some service, but since this is purely for learning purposes you can hardcode it in the script for checking. So, the final solution can be similar to this:
<body>
<form>
<!-- user-id -->
<input id="user" type="text" />
<!-- user-password -->
<input id="pass" type="password" />
<button id="btn">Enter</button>
</form>
<script>
const myPass = "SomePassword";
document.getElementById("user").value = "UsernameOrId"; // predefining the value simulating is saved and by default filled up
document.getElementById("pass").value = myPass; // predefining the value simulating is saved and by default filled up
const btn = document.getElementById("btn"); // getting the button to control its behavior on click event
btn.addEventListener("click", function () {
const passWhenClickingTheBtn = document.getElementById("pass").value;
if (myPass === passWhenClickingTheBtn) { // checking the value entered for pass
window.open("./index.html");
}
});
</script>

Related

when I clicked the submit button it should take the value of the description and write it down in another page how could I do it with JavaScript code [duplicate]

I have one simple html page with a text field that asks for user's name. i want to save what user enter and on another page i want to retrieve that name and say hello + (user's name).
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>LocalStorage</title>
</head>
<body>
<form>
<p>Enter your name</p>
<input type="text">
<button type="submit" value="submit">Submit</button>
</form>
</body>
</html>
and the second page is where the data from first page comes (through localStorage).
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>secondPage</title>
</head>
<body>
<h1>Hello </h1>
</body>
</html>
thank you.
I'm not sure if this is a homework assignment but this should get you started.
It will involve:
First storing the data into localStorage
Then directing the user over to the second page - most likely through window.location.href.
Then pulling the data back out of localStorage to display there.
Here's a jsfiddle to get you started setting and getting data.
https://jsfiddle.net/em92zbod/
The two main functions are:
window.localStorage.setItem("key", "value");
window.localStorage.getItem("key");
Where "key" is any identifier you want to use for the value.
Here's a suggested approach by using sessionStorage.
However, you can also use localStorage with the same implementation method. The only differences between them is localStorage will keep the data even if you close your browser. Which in this case, saving userName I think it's better to use sessionStorage.
1.html
<form action="2.html" onsubmit="callme()">
<p>Enter your name</p>
<input id="tbName" type="text">
<button type="submit" value="submit">Submit</button>
</form>
<script>
function callme(){
var name = document.getElementById('tbName').value;
sessionStorage.setItem('userName', name);
}
</script>
2.html
<h1 id="welcome"> </h1>
<script>
window.onload = function() {
document.getElementById('welcome').innerText = "Hello, " + sessionStorage.getItem('userName');
};
</script>
Code update
page 1
window.addEventListener("DOMContentLoaded", () => {
document.getElementById("myForm").addEventListener("submit", e => {
const form = e.target;
const name = document.getElementById('tbName').value;
sessionStorage.setItem('userName', name);
})
})
<form action="2.html" id="myForm">
<p>Enter your name</p>
<input id="tbName" type="text">
<button type="submit">Submit</button>
</form>
Page 2
window.addEventListener("DOMContentLoaded", () => {
document.getElementById('welcome').textContent = `Welcome ${ sessionStorage.getItem('userName') || "stranger"}`;
})
<h1 id="welcome"></h1>

clear input field when text is entered into another input field

I have a Currency Converter , consisting of two fields and a button. In the first field I type the amount I want to be converted, in the second field I get the result of the conversion.
The question is:
When I type text in the first field, how can I clean up the text from the second field with the conversion result? Using a Javascript / Jquery function?
Thanks in advance.
This is my code:
function convertiLireInEuro() {
var importoInserito = $('#txtLireEuro').val();
importoInserito = importoInserito.replace(/,/g, '.');
var lire = parseFloat(importoInserito)
var euro = lire * 1000 / 1936.27
euro = euro.toFixed(2);
euro = Math.round(euro);
$('#txtConversione').val(euro); }
HTML:
<input type="text" id="txtLireEuro" name="txtLireEuro" style="text-align:right" onkeypress="return onlyNumbers(event);" /> 000 ₤
<input value="Converti in Euro" type="button" id="btnLireEuro" name="btnLireEuro" style="margin-left: 20px" onclick="convertiLireInEuro();highlightAndCopyText();"/>
<input type="text" id="txtConversione" name="txtConversione" style="text-align:right;margin-left:20px" readonly /> €
<span class="Label" style="margin-left:12px">(importo già arrotondato all’intero e incollabile nel campo desiderato)</span>
Here is what you need, I post a coding snippet. I have 2 fields, typing-field and field-to-reset. If you first fill in the field-to-reset with some text and then start typing in typing-field the field-to-reset will reset.
let typing = document.getElementById("typing-field");
let reset = document.getElementById("field-to-reset");
typing.addEventListener("keydown", () => {
reset.value = "";
})
<!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>
</head>
<body>
<div>Typing field:</div>
<input id="typing-field" type="text">
<div>Field to reset:</div>
<input id="field-to-reset" type="text">
</body>
</html>
HTML Code
<body>
<input type="text" id="input_box">
<input type="text" id="result_box">
</body>
JQuery Code
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#input_box").keydown(function(){
$("#result_box").val("");
})
});
</script>
<body>
<input type="text" id="input_box">
<input type="text" id="result_box">
</body>
When "Input_box" is getting focus on click the result_box will clear
it's value.
You already have an onkeypress event listener named onlyNumbers. You can simply put $('#txtConversione').val = ""; in that function.

HTML pages still accessible without login

I am building a site on Glitch.com for me and my friends. I already know HTML/CSS, and am learning JS.
Even though it's not that secure, I want the login system to be made out of JS since this project is just for fun and to improve my skills.
I currently have the login page with HTML/CSS, and wrote a few JS if statements for the login validation. I want the users who are logged in successfully to be redirected to another page, home.html.
However, I can still access home.html by just inserting /home.html to the end of the link, not requiring sign in. How do I fix this?
HTML code for login:
<!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">
<title>Login for Access</title>
<link rel="stylesheet" href="/login.css">
<script src="/login.js" defer></script>
</head>
<body>
<h1>Login for Access</h1>
<p id = "access-denied">Incorrect User ID/Password</p>
<form id = "login-form">
<label for="user_id">User ID:</label>
<input type="number" id="user_id" name="user_id" required><br><br>
<label for="pwd">Password:</label>
<input type="password" id="pwd" name="pwd" required><br><br>
<input type="submit" value= "Submit" id = "login-submit">
</form>
</body>
</html>
JS code:
const loginForm = document.getElementById("login-form");
const loginButton = document.getElementById("login-submit");
const loginErrorMsg = document.getElementById("access-denied");
loginButton.addEventListener("click", (e) => {
e.preventDefault();
const user_id = loginForm.user_id.value;
const password = loginForm.pwd.value;
if (user_id === "id" && password === "pass") {
window.location.href="home.html";
} else {
loginErrorMsg.style.opacity = 1;
}
})
Sorry if anything is unclear. It would be greatly appreciated if someone could edit this for more clarity.
You can't use client-side code to stop people accessing pages. Client-side code is ultimately under the console of the owner of the browser.
Authentication/Authorisation has to be done server-side.

How do you make a submit button redirect to another page after the user has inputted the correct password?

could you please help me find out what's wrong? After login, it is supposed to redirect you to another page, but nothing happens. The user name is: Joshua and the password is: Joshua#123.
<html>
<head>
<title>Login: MessengerX</title>
<link rel="stylesheet" type="text/css" href="C:\Users\Tania\Documents\Website\style.css">
<meta charset="UTF-8">
<meta name="description" content="HTML website called MessengerX. Send messages to anyone who has logged in.">
<meta name="author" content="Joshua Hurley">
<meta name="keywords" content="HTML, MessengerX, Joshua Hurley, Website, Supremefilms">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="css/style.css" />
<script type="text/javascript">
var attempt = 3; // Variable to count number of attempts.
// Below function Executes on click of login button.
function validate() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
if (username == "Joshua" && password == "Joshua#123") {
alert("Login successfully");
location.replace("www.youtube.com"); // Redirecting to other page.
} else {
attempt--; // Decrementing by one.
alert("You have " + attempt + " attempt left;");
// Disabling fields after 3 attempts.
if (attempt == 0) {
document.getElementById("username").disabled = true;
document.getElementById("password").disabled = true;
document.getElementById("submit").disabled = true;
return false;
}
}
}
</script>
<script src="js/login.js"></script>
</head>
<body>
<div class="imgcontainer">
<img src="C:\Users\Tania\Documents\Website\Screenshots\face.jpg" height="500" alt="Avatar" class="avatar">
</div>
<div class="container">
<div class="main">
<h1 style="color:"><b><i>Login: MessengerX</i></b></h1>
<form id="form_id" method="post" name="myform">
<label>User Name :</label>
<input type="text" name="username" id="username" />
<label>Password :</label>
<input type="password" name="password" id="password" />
<button type="submit" value="Login" id="submit" onclick="validate()" />
</form>
<b><i>Submit</i></b>
</div>
</div>
</body>
</html>
Try this:
window.location.replace("https://www.youtube.com")
You can move code inside window.addEventListener('load' or you can move script after dom at the end
Suggestion: use the entire URL with HTTP or HTTPS.
location.replace("https://www.youtube.com");
<script type="text/javascript">
window.addEventListener('load', (event) => {
var attempt = 3; // Variable to count number of attempts.
/// code here
});
</script>
As leonardofmed mentioned, better place your script just befor </body> closing tag,
because you need to load html first, so script can see elements, otherwise at it's start there is no elements yet, so this will cause error, as for redirecting you can use:
// Simulate a mouse click:
window.location.href = "http://www.w3schools.com";
// Simulate an HTTP redirect:
window.location.replace("http://www.w3schools.com");
use <form><button type="button" ... instead
<form><button type="submit" ... has its own logic ("magic"), which is doing the problem.
use protocol in url location.replace("https://www.youtube.com"), otherwise it's relative path
BTW never validate password on client!!!

LocalStorage - save name through form - show on other page

I have one simple html page with a text field that asks for user's name. i want to save what user enter and on another page i want to retrieve that name and say hello + (user's name).
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>LocalStorage</title>
</head>
<body>
<form>
<p>Enter your name</p>
<input type="text">
<button type="submit" value="submit">Submit</button>
</form>
</body>
</html>
and the second page is where the data from first page comes (through localStorage).
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>secondPage</title>
</head>
<body>
<h1>Hello </h1>
</body>
</html>
thank you.
I'm not sure if this is a homework assignment but this should get you started.
It will involve:
First storing the data into localStorage
Then directing the user over to the second page - most likely through window.location.href.
Then pulling the data back out of localStorage to display there.
Here's a jsfiddle to get you started setting and getting data.
https://jsfiddle.net/em92zbod/
The two main functions are:
window.localStorage.setItem("key", "value");
window.localStorage.getItem("key");
Where "key" is any identifier you want to use for the value.
Here's a suggested approach by using sessionStorage.
However, you can also use localStorage with the same implementation method. The only differences between them is localStorage will keep the data even if you close your browser. Which in this case, saving userName I think it's better to use sessionStorage.
1.html
<form action="2.html" onsubmit="callme()">
<p>Enter your name</p>
<input id="tbName" type="text">
<button type="submit" value="submit">Submit</button>
</form>
<script>
function callme(){
var name = document.getElementById('tbName').value;
sessionStorage.setItem('userName', name);
}
</script>
2.html
<h1 id="welcome"> </h1>
<script>
window.onload = function() {
document.getElementById('welcome').innerText = "Hello, " + sessionStorage.getItem('userName');
};
</script>
Code update
page 1
window.addEventListener("DOMContentLoaded", () => {
document.getElementById("myForm").addEventListener("submit", e => {
const form = e.target;
const name = document.getElementById('tbName').value;
sessionStorage.setItem('userName', name);
})
})
<form action="2.html" id="myForm">
<p>Enter your name</p>
<input id="tbName" type="text">
<button type="submit">Submit</button>
</form>
Page 2
window.addEventListener("DOMContentLoaded", () => {
document.getElementById('welcome').textContent = `Welcome ${ sessionStorage.getItem('userName') || "stranger"}`;
})
<h1 id="welcome"></h1>

Categories

Resources