【问题标题】:how can i protect my index.html website by js so i can only open it on my pc?我如何通过 js 保护我的 index.html 网站,所以我只能在我的电脑上打开它?
【发布时间】:2022-01-11 12:20:02
【问题描述】:

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

【问题讨论】:

  • 你使用什么后端?
  • 我使用 java 脚本,我只想让它成为个人而不是互联网,只是在我的电脑上学习
  • 没有后端就无法做到这一点。
  • 哦,那么我们如何使用后端来做到这一点?
  • 第一步,为后端选择语言/框架/库。 PHP 是编写简单后端的良好第一语言。或者,您可以在 Node.js、Deno 或 Rhino 等引擎中使用 JavaScript,但恕我直言,这有点复杂,对初学者不太友好。

标签: javascript java web passwords


【解决方案1】:

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

【讨论】:

  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
【解决方案2】:

首先,您必须向该输入添加一个 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>

【讨论】:

  • 谢谢你的帮助♥
  • 不客气,如果确实对您有所帮助,请接受此答案。谢谢!
猜你喜欢
  • 2011-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多