Home > Web Front-end > JS Tutorial > body text

How to Pass Variables between Pages in JavaScript using Local Storage?

Mary-Kate Olsen
Release: 2024-10-24 07:52:01
Original
1000 people have browsed it

How to Pass Variables between Pages in JavaScript using Local Storage?

Passing Variables through JavaScript from Page to Page

Your goal is to pass a variable's value from "page 1" to "page 2," and display it using window.onload. However, the global variable approach you're using appears to be causing problems.

Local Storage: A Different Approach

Instead of relying on global variables, consider utilizing the localStorage API. This approach allows you to store data locally in the browser, independent of individual pages. Here's a revised solution using localStorage:

page1.html

<code class="html"><script>
  window.onload = function() {
    var getInput = prompt("Enter your value:");
    localStorage.setItem("myValue", getInput);
  };
</script>

...

<input type="submit" value="Go To Page 2" onclick="location.href='page2.html'"></code>
Copy after login

page2.html

<code class="html"><script>
  window.onload = function() {
    var getValue = localStorage.getItem("myValue");
    alert("Value from page 1: " + getValue);
  };
</script></code>
Copy after login

This approach avoids the global variable issues you were encountering and allows you to pass the variable's value effectively between the two pages.

The above is the detailed content of How to Pass Variables between Pages in JavaScript using Local Storage?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!