0

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 ?

2
  • 4
    use localStorage for this purpose. Commented Mar 8, 2014 at 15:20
  • localStorage is only for HTML5 browsers. Commented Mar 8, 2014 at 15:24

2 Answers 2

2

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()
Sign up to request clarification or add additional context in comments.

2 Comments

Why do I have to use .clear() function. Shoudnt, the session be cleared out once i close the browser.
There will be users who don't simply close the browser. Just a precaution. Anyway, it's up to you.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.