Is it possible to load a variable from a JS script in another HTML file?

Viewed 243

I have a JS script inside a HTML file that get a certain value from API and put on a variable. I want to put that same variable with the value on another HTML file (The new HTML file is loaded from a button in the previous page). Is there any way to to that?

1 Answers

I can think of two easy ways.

1.) Try out sessionStorage: sessionStorage.setItem('key', variable); will store the variable value in the browser session storage. sessionStorage.getItem('key'); will return the set value of said variable.

See: https://developer.mozilla.org/de/docs/Web/API/Window/sessionStorage

2.) Add the variable value to your url www.yourdomain.com?key=value and retrieve it from your second script.

const urlString = window.location.href;
const url = new URL(urlString);
const value = url.searchParams.get("key");

See: How to get the value from the GET parameters?

Related