简体   繁体   中英

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

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?

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM