How to pass variables through JavaScript from one html page to another page?

Estimated read time 2 min read

There are several ways to pass variables from one HTML page to another using JavaScript:

  1. URL parameters: You can pass data as URL parameters when redirecting the user to a new page. For example:
window.location.href = "second.html?variableName=" + value;

In the second HTML page, you can access the URL parameters using the URLSearchParams object, like this:

const params = new URLSearchParams(window.location.search);
const variableName = params.get("variableName");
  1. Local Storage: You can use the localStorage API to store data in the browser’s local storage, which can be retrieved from other pages. For example:
localStorage.setItem("variableName", value);

In the second HTML page, you can retrieve the data from local storage, like this:

const variableName = localStorage.getItem("variableName");
  1. Cookies: You can use the document.cookie property to set a cookie that can be retrieved from other pages. For example:
document.cookie = "variableName=" + value;

In the second HTML page, you can retrieve the value of the cookie using JavaScript, like this:

const cookies = document.cookie.split(";");
for (let i = 0; i < cookies.length; i++) {
  const cookie = cookies[i].trim();
  if (cookie.startsWith("variableName=")) {
    const variableName = cookie.substring("variableName=".length);
    break;
  }
}

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply