Home >Web Front-end >JS Tutorial >How to Pass Variables Between HTML Pages in JavaScript with Scope Limitations?
Passing Variables in JavaScript Between HTML Pages
You encounter an issue when attempting to pass a variable from one HTML page (page 1) to another (page 2) using JavaScript. Despite your efforts to declare a global variable, the value remains undefined on page 2. This article aims to provide a solution to this problem by exploring the limitations of JavaScript variables and offering an alternative approach.
Understanding JavaScript Variable Scope
JavaScript variables have a specific scope, which determines the parts of the code where they can be accessed. The code you provided declares a variable price outside of any function, attempting to make it global. However, JavaScript only recognizes variables declared globally with the var keyword within the script tags at the beginning of the HTML document.
Using LocalStorage for Cross-Page Communication
Instead of relying on global variables, a more robust approach for cross-page communication is to use LocalStorage. LocalStorage allows you to store key-value pairs that persist even when the page is refreshed or the browser is closed.
Page 1 Code:
<code class="html"><script type="text/javascript"> window.onload = function() { var getInput = prompt("Hey type something here: "); localStorage.setItem("storedPrice", getInput); } </script></code>
Page 2 Code:
<code class="html"><script type="text/javascript"> window.onload = function() { alert(localStorage.getItem("storedPrice")); } </script></code>
This approach stores the entered value in LocalStorage on page 1 and retrieves it on page 2 when the page loads. LocalStorage is supported by modern browsers and provides a reliable mechanism for cross-page communication.
The above is the detailed content of How to Pass Variables Between HTML Pages in JavaScript with Scope Limitations?. For more information, please follow other related articles on the PHP Chinese website!