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

会有一股神秘感。 提交于 2021-01-27 18:16:50

问题


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:


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?



来源:https://stackoverflow.com/questions/62314910/is-it-possible-to-load-a-variable-from-a-js-script-in-another-html-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!