如何通过js保护我的index.html网站,使我只能在我的电脑上打开它



我想用一些js来保护我的本地静态html网站密码,这样当我在电脑中打开本地html文件时,它会附带一个表格来填写我保存的用户id和我自己的密码,当我点击回车键时,只有在密码正确的情况下才能打开我的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>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> `` 

这不是一种正确的方法。你需要一个后端来正确执行它。但如果只是为了玩,你可以有一个警告框,只需比较它们的值:如果正确,它就会显示出来。

首先,您必须向输入添加一个id或一个类,以便在脚本部分中选择它们。之后,您可以选择它们并添加任何您想要的值。例如:

<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>

为了进行比较,您应该从数据库或某些服务之类的地方获得正确的密码,但由于这纯粹是为了学习,您可以在脚本中对其进行硬编码以进行检查。因此,最终的解决方案可以类似于此:

<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>

最新更新