简体   繁体   中英

Why can't I use globals in separate html and js files?

I have two html files: index.html and lobby.html. In main.js, which I load in index.html, lobby.html is loaded using window.location.href. I have tried every way of defining globals in main.js (namespaces such as: var Global = {}; Global.variableName = 0; ... Global.variableName = whatever; , simply defining variables out of function scopes: var myGlobal; and even using window. to define and use globals: window.myGlobal = 0; ... window.myGlobal = whatever; ). No matter any of these approaches, every time I try to access these "globals" in a separate script in lobby.html, it always throws an undefined error. How does this make any sense?

The answer to your first question, Why can't I ...? , is that you start a new session whenever you load a page. So, any of the Javascript variables from the previous session are gone.

The other (implied) question, How can I keep the value of Javascript variables across sessions? is either to use cookies in Javascript (MDN) or append request variables to the end of your URL then process them when the new page loads: GET (SO)

When a new page is loaded, you are essentially starting a new session as explained by others here and hence the data will be reset. For retaining some data across pages, you could use HTML5 Web storage - Session storage or Local storage as per your business needs.

MDN source

The two mechanisms within Web Storage are as follows:

  • sessionStorage maintains a separate storage area for each given origin that's available for the duration of the page session (as long as the browser is open, including page reloads and restores).
  • localStorage does the same thing, but persists even when the browser is closed and reopened.

W3Schools

HTML local storage provides two objects for storing data on the client:

~ window.localStorage - stores data with no expiration date

~ window.sessionStorage - stores data for one session (data is lost when the browser tab is closed)

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