Home >Web Front-end >JS Tutorial >How to Pass Variables Between HTML Pages Securely with JavaScript?

How to Pass Variables Between HTML Pages Securely with JavaScript?

DDD
DDDOriginal
2024-10-24 08:03:301053browse

How to Pass Variables Between HTML Pages Securely with JavaScript?

Passing Variables Between HTML Pages with JavaScript

In web development, it is often necessary to transfer data between two HTML pages. One common approach is to use JavaScript to store data in a global variable and retrieve it on the second page. However, this method can encounter issues if the global variable is not properly declared or accessed.

Consider the following scenario:

  • You have two pages, "page 1" and "page 2".
  • On page 1, a textbox contains a value (e.g., 100).
  • Upon clicking a button, JavaScript saves the textbox value in a global variable and redirects to page 2.
  • On page 2, an onload function attempts to retrieve and display the value stored on page 1.

However, the onload function always returns "undefined" for the global variable.

Solution Using Local Storage

To resolve this issue, an alternative approach is to utilize localStorage. Local storage provides a more reliable and secure way to store and retrieve data.

  • On page 1:

    Store the textbox value in localStorage using the setItem() method, as follows:

    <code class="javascript">window.onload = function() {
      var getInput = prompt("Hey type something here: ");
      localStorage.setItem("storageName", getInput);
    }</code>
  • On page 2:

    Retrieve the stored value from localStorage using the getItem() method and display it using alert(), as shown below:

    <code class="javascript">window.onload = function() {
      alert(localStorage.getItem("storageName"));
    }</code>

By using localStorage, you can ensure the consistent storage and retrieval of data between different HTML pages. This approach is both reliable and efficient.

The above is the detailed content of How to Pass Variables Between HTML Pages Securely with JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn