简体   繁体   中英

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM