Home  >  Article  >  Web Front-end  >  How to Pass a Variable between HTML Pages using JavaScript Effectively?

How to Pass a Variable between HTML Pages using JavaScript Effectively?

Barbara Streisand
Barbara StreisandOriginal
2024-10-24 07:58:30322browse

How to Pass a Variable between HTML Pages using JavaScript Effectively?

Passing Variable through JavaScript from One HTML Page to Another

Problem:

You need to pass a variable between two HTML pages using JavaScript. The variable's value is captured in a text box on the first page, and you want to access that value on the second page after the user clicks a button. However, you are encountering an "undefined" value when attempting to retrieve the variable on the second page.

Solution:

Using localStorage:

Instead of using global variables, which can be unreliable and difficult to manage, you can utilize localStorage to achieve this functionality. localStorage is a browser API that provides a way to store data locally in the browser, even after closing the app or browser tab. It has a large storage limit compared to cookies.

Implementation:

  1. On Page 1 (Save Variable):

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

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

Explanation:

  • On Page 1, you use localStorage.setItem("storageName", getInput) to store the value entered in the text box in the storageName key of localStorage.
  • On Page 2, you use localStorage.getItem("storageName") to retrieve the value stored in the storageName key and display it in an alert box.

Alternative Approaches:

  • Cookies: You can also use cookies to pass the variable, but they have a smaller storage limit and are sent back to the server with every request, which may impact performance and privacy.
  • Session Storage: Session storage is similar to localStorage but only lasts for the current session and is cleared when the user closes their browser tab. It can be used if you only need to store data for a specific session.

The above is the detailed content of How to Pass a Variable between HTML Pages using JavaScript Effectively?. 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