Skip to content

How to Pass Variables Between HTML Pages in JavaScript

Learn how to share data between pages using Web Storage (localStorage/sessionStorage) for complex objects or URL query parameters for simple, shareable values in JavaScript.

Because the web is stateless, variables from one page are not automatically available on another. To share data between pages, such as user preferences, a session ID, or the result of a form submission, you must use a specific technique to persist the data during navigation.

This guide will teach you the two primary client-side methods for passing variables between pages: using Web Storage (localStorage or sessionStorage) for complex or private data, and using URL Query Parameters for simple, shareable data.

Web Storage (localStorage and sessionStorage) is the most robust and common way to pass data between pages on the same domain. It allows you to store strings, and by using JSON, you can easily store complex objects and arrays.

Storing Data on the First Page

On your first page, you use localStorage.setItem() to save a key-value pair. The value must be a string. To store objects or arrays, you must first convert them to a JSON string using JSON.stringify().

Page page1.html:

<!DOCTYPE html>
<html>
<head>
  <title>Page 1</title>
</head>
<body>
  <h1>Sending Data</h1>
  <a href="page2.html">Go to Page 2</a>

  <script>
    // Storing a simple string
    const username = 'Alice';
    localStorage.setItem('username', username);

    // Storing an object (must be converted to a string)
    const settings = { theme: 'dark', notifications: true };
    localStorage.setItem('userSettings', JSON.stringify(settings));
  </script>
</body>
</html>

Retrieving Data on the Second Page

On the second page, you use localStorage.getItem() to retrieve the stored string. If you stored an object or array, you must parse it back from a JSON string using JSON.parse().

Page page2.html:

<!DOCTYPE html>
<html>
<head>
  <title>Page 2</title>
</head>
<body>
  <h1>Received Data</h1>

  <script>
    // Retrieving the simple string
    const username = localStorage.getItem('username');
    console.log('Username:', username);     // Output: 'Alice'

    // Retrieving and parsing the object
    const settingsString = localStorage.getItem('userSettings');
    const settings = JSON.parse(settingsString);
    console.log('Theme:', settings.theme);  // Output: 'dark'
  </script>
</body>
</html>

localStorage vs. sessionStorage: A Key Difference

Web Storage offers two mechanisms:

  • localStorage: Persists even after the browser is closed and reopened. It's great for storing long-term user preferences.
  • sessionStorage: Persists only for the duration of the page session (i.e., until the tab is closed). It's perfect for passing data between pages in a single workflow, as the data is automatically cleared when the user is done.

Method 2 (For Simple, Shareable Data): URL Query Parameters

Query parameters are key-value pairs added to the end of a URL. This method is ideal for passing simple, non-sensitive data, as the state is contained directly in the link, which can be bookmarked or shared.

Sending Data from the First Page

You construct a URL with a query string, which starts with ? and separates pairs with &.

Page page1.html:

<!DOCTYPE html>
<html>
<body>
  <h1>Sending Data via URL</h1>
  <a id="link-to-page2" href="page2.html">Go to Page 2 with Data</a>

  <script>
    const link = document.getElementById('link-to-page2');
    const userId = 123;
    const source = 'homepage';

    // Construct the query string
    link.href = `page2.html?userId=${userId}&source=${source}`;
  </script>
</body>
</html>

Retrieving Data on the Second Page

The easiest and most reliable way to parse query parameters is with the built-in URLSearchParams object.

Page page2.html:

<!DOCTYPE html>
<html>
<body>
  <h1>Received Data from URL</h1>

  <script>
    // Get the query string part of the URL
    const queryString = window.location.search;
    
    // Create a new URLSearchParams object
    const urlParams = new URLSearchParams(queryString);

    // Get values by their key
    const userId = urlParams.get('userId');
    const source = urlParams.get('source');

    console.log('User ID:', userId); // Output: '123'
    console.log('Source:', source);  // Output: 'homepage'
  </script>
</body>
</html>

Crucial Step: URL Encoding

If your parameter values might contain special characters like spaces, &, or ?, you must encode them with encodeURIComponent() to prevent the URL from breaking.

const searchTerm = 'laptops & notebooks';
const encodedTerm = encodeURIComponent(searchTerm); // "laptops%20%26%20notebooks"
const url = `search.html?query=${encodedTerm}`;

When to Use Each Method: A Comparison

Feature Web Storage (localStorage/sessionStorage) URL Query Parameters
Data Types Complex (Objects/Arrays via JSON) Simple (Strings/Numbers)
Persistence Session or permanent None (only in the URL)
Shareability Not shareable (stored in browser) Easily shareable (part of the link)
Security Not visible in the URL bar Visible to everyone in the URL bar
Size Limit High (approx. 5 MB) Low (approx. 2,000 characters)
Best For User sessions, complex state, private data Search queries, filters, simple IDs

Conclusion

Passing variables between pages is a fundamental task with two excellent client-side solutions.

  • Use Web Storage (localStorage or sessionStorage) when you need to pass complex data (objects, arrays), when the data should persist across multiple page navigations, or when the data should not be visible in the URL.
  • Use URL Query Parameters when you are passing simple, non-sensitive data and want the page's state to be shareable and bookmarkable through its URL. Always remember to use encodeURIComponent() for the values.
Navigation