0

Say I want to have a global object which can be visible and accessible across pages(??)

// core.js
var MyLib = {}; // global Object cointainer
MyLib.value = 1;

If I define this way, then I can have access to MyLib.value in other places as long as I load the core.js.

However, if I want to add new property to object MyLib in somewhere else, say:

//extra.js
MyLib.otherVal = 2;

Then I try to access MyLib.otherVal from a different place, it is not available. I probably have some fundamental misunderstanding on how this suppose to work. I hope someone can enlighten me.

After reading the comments, I realized the scope I want is indeed across pages. Is that even possible?

thanks

Oliver

3
  • 3
    What do you mean by "from a different place"? Are you including both files? Commented Mar 15, 2011 at 16:50
  • 2
    If you mean on another page - that is how it is supposed to behave. Reloading/navigating to a web page clears all JavaScript memory (variables etc.). Commented Mar 15, 2011 at 16:55
  • 1
    It definitely will work if 1. you import "core.js" before "extra.js", and 2. all your references in "other places" are in the same page in scripts executed after the first two. Commented Mar 15, 2011 at 17:10

1 Answer 1

1

If you want to carry data across pages, there are really three major methods:

  1. LocalStorage. See this page for a fairly thorough explanation of the concept, how to use it, and so forth. Here is a library dealing with JavaScript storage.
  2. Cookies. Cookies can store 4KiB of data, but some users disable them.
  3. window.name. You can store up to 2MiB of data in window.name. Here is a library that focuses on storing data in window.name; it seems fairly well-written.

You could potentially write an app to take advantage of all three of these techniques, starting with LocalStorage and falling back to window.name if all else fails.

Sign up to request clarification or add additional context in comments.

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.