简体   繁体   中英

passing variables from a javascript file to another html page

I have a variable value in one javascript file. How do I access this variable in another html page, value when a user clicks that particular html link. I have tried to use the concept of set and get cookies based on the variable, so that I can access this variable in another html page. Is there any other way to achieve this ?

Use sessionStorage!

In the first page, initiate the value inside sessionStorage, for example I'm passing a userID value 24. Here's how you set it;

sessionStorage.userID = 24

Then, here's how to access it anywhere else;

console.log(sessionStorage.userID) // = 24

On logout, remember to clear it!

sessionStorage.clear()

You can also adapt the link to encode the information. Change the href with javascript.

Either add a query string: Or add a hash:

Second one might be safer as it doesn't depend on how your server handles queries, it should preserve the hash.

Once on the new page use javascript again to get the info back from the current url using window.location

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