javascript object memory and webpages - javascript

Suppose a javascript holds an object on page A (www.example.com/a.html)
Suppose the user clicks on page B (same domain) (www.example.com/a.html)
is it possible for the javascript on page B to access the object from a.html ?
I don't want tricks to transfer the object, like posting to the webserver or adding parameters to the url.
Thanks,
E
p.s.
Just adding this 'p.s.' following some of the answers:
Using a cookie is not an option because the data on page A would be very very very large.

There's no direct way for page B to access the object, because the object will no longer exist once page A is unloaded. As other answers note, you can store the object somewhere, and then page B can get a copy of the original object from page A.
A cookie is another alternative to local storage.

Not a true solution but html5 localstorage might be an option. (That is if you want to live on the bleeding edge of web technology.)
And the best part: it does not include any post/url tricks as you requested. :-)

Check out the jStorage plugin here: http://www.jstorage.info/ Works on almost all engines that matter: Trident, Gecko, Webkit, etc.
Its a simple way to store objects.

In general, no -- state is not preserved between requests in a browser. When you navigate between pages, the first page is completely unloaded (DOM, Javascript variables, etc.) and the second page is then loaded.
There are some ways that you can preserve data outside of Javascript without hitting the server though, such as cookies, or HTML5's localstorage as Chris mentioned.

What about saving the serialised object in a Cookie using JSON?

Related

Find the last visited URL in javascript with history

I know about document.referer and this is not what I'm looking for.
It could probably be a solution but I want to retrieve it in local without using server.
Steps :
I'm pushing a new state in the current url of my page with history.pushState('','','#test')
I'm going to the next page.
And now I want to retrieve the URL but history.previous has been erased since Gecko 26.
Is there an other way of getting this value except from using cookies or sessionStorage?
One way of doing it would be to put the value in a parameter of the next page address, like so:
http://server.com/next-page-address/whatever.html?prevData=RequiredStateData
Note that using this approach, you might be exposed to users changing RequiredStateData in a malicious way. You can protect yourself using encryption or some checksum field.
So my problem was that there is no option for that purpose in local without a server environment.
If you find this question it's that you're probably in the same problem as me so the only option I found was to use.
sessionStorage.setItem('foo',val) and retrieve it with sessionStorage.getItem('foo').

"Null" HTML DOM Element?

I'm writing a framework which uses javascript/html as the client and it-doesn't-matter as the back end.
From time to time I have a need to store data in the HTML DOM. Ideally I'd like to store the data against a DOM element, but I want this element to have no UI impact.
At the moment I'm thinking I'll use a <span> with no text content and decorate it with attribution so that my framework can pick up that it is a data container and behave appropriately.
Is there a better choice? (For the avoidance of doubt, I know there are other ways I could do things - I'm not interested in these, purely in what the best HTML element to use to contain data without having a UI impact).
Edit (explanation of architecture):
I've created a server-side technology which is based on top of a generic reporting engine I've previously created. This server-side thing essentially works as a web-server - this might seem like an unusual choice to make but, given organisational constraints, it's the best choice - for the sake of argument, assume this is true. One of the things I need this system to do is to generate dynamic forms to capture data which is in a tree-like form. This has been fine and has worked well - my question is because when a sub-form is hidden (for example, the user has made all required decisions in a given sub-section of the data), I destroy the data capture elements - if the form is embedded within a parent form which needs access to the data captured in a destroyed sub-form, I need a way of embedding the data into the DOM so it can be collected to be passed back to the server. The requirements are a lot more complicated that this, but it'll take far too long to detail them all.
Well (and for the avoidance of doubt), the HTML elements are not supposed to store data. If you really want to, use the <input type="hidden"> element.
For your purpose, I recommend (in that order) using localstorage or cookie or web database.
here are some resources :
localstorage : http://diveintohtml5.info/storage.html
cookie : http://www.the-art-of-web.com/javascript/setcookie/
web database : http://www.tutorialspoint.com/html5/html5_web_sql.htm
As JLRishe pointed out, if you need, for whatever reason, a text node storage, then span is a good choice as div is (and as lot of elements are as long as you display: none them).
You could just create javascript objects...
var myData ={
property1:"aaaaa",
property2:500,
property3:{morestuff1:"AAA", ... },
property3:["list1", "list2", ... ],
....
}
Easy to access and easy to manipulte within the DOM if you need.
No UI impact.... (no render)
The obvious choice here is to use HTML data attribute. If you have a table and want to store info about the table that is not shown to the user - you could just:
<table id="mytable" data-id="2000" data-rows="20" data-whatever="whatever">
You could then get it with jQuery easely with:
$("#mytable").data('rows');
Which would give you 20.
It's not good practice to store data in the DOM, if you're not actually using it for the purpose of layout. Yikes!
To better suit your needs, HTML5 provides a JavaScript API for handling client side storage. Depending on your circumstances, you have 2 options to choose from. The APIs are exactly the same, the only difference is the lifetime of the storage.
They are:
localStorage: Local storage is persistent; data stored in local storage is even available to the webpage after the user closes the browser completely and reopens it.
sessionStorage: As the name says, this data is only available for the current session.
Here's a link that will help you better understand these APIs so you can solve your particular problem: http://www.w3schools.com/html/html5_webstorage.asp

Using the window object for session storage instead of AmplifyJS store

I'm using AmplifyJS Store. I think it's a good wrapper for persistent storage. I've been using it in a JQuery plugin and it works pretty well.
Lately though, I've been wondering if I can just do the same thing using a namespace variable in the window object?!
AmplifyJS Store + JSON2.js (required for data serialization) costs me 22Kb (8Kb minified) of file size alone, not to mention the additional supporting code I've had to create around it. Also, I'm using only sessionStorage (i.e. I have no need for persistence after the browser window closes, only while the window is active).
So, is there really any major reason I can't use the window object instead of AmplifyJS Store for my specific circumstance?! I've thought about the expiry feature but I can easily build in same functionality in a few lines of code.
Thanks.
HTML5 localStorage in window object by itslef has a very simple api:
var valueOfName = window.localStorage.getItem("name");
window.localStorage.setItem("name", "value");
you can even omit global window object:
var valueOfName = localStorage.getItem("name");
localStorage.setItem("name", "val");
moreover you can apply array-style notation:
var valueOfName = localStorage["name"];
localStorage["name"] = "value";
that is it! And it doesn't have an expire date, URL strings or other complications in its API which took place in elder cookies-approach. All what AmplifyJs provides (as I can see) is a support for older browsers (who were using cookies) by givin' you the same API as original localStorage does.
In other words if you are not targeted on Netscape Navigator, Mosaic and IE 7 you can forget about using of AmplifyJS and apply native localStorage API.
However despite an approach, you should never rely on client-side persistance for sure, because it is totally dependent from local browser (client could simply clear cache, reinstall something or sign-in from other computer) - use server-side databases and similiar technologies for saving user's info.
If you are actually trying to save persistent data (data that is still there if the page reloads or the user navigates away), storing it on the window object is not an option. The data won't be there when you check for it later.

Store Javascript variable client side

Not duplicate : I've read many questions like this and it always ended up "use PHP or server-side stuff, and watch out for injection/data manipulation".
I want to store simple stuff on the client side (save and load), like a Google Map location, and want it to stay between refresh of the page.
I don't want to use PHP or any server-side thing.
How can I proceed ?
Thanks
You can use cookies or localStorage.
If html5 is not a problem I would say localstorage is the way to go:
//set value
localStorage.setItem('todoData', this.innerHTML);
//read value
if ( localStorage.getItem('todoData') ) {
edit.innerHTML = localStorage.getItem('todoData');
}
ripped from
http://net.tutsplus.com/tutorials/html-css-techniques/quick-tip-learning-about-html5-local-storage/ :-)
There are multiple options to store data in client side - IndexedDB, localstorage, webSQL, SessionStorage, Cookies, etc.
IndexedDB
Data can be queried efficiently. No limitation in size( but volume or
disk drivers limits the size )
It will store in Key-Object format
It will not be supported in safari browser
Support Queries
Asynchronous
localstorage
It will store value in key-value format (value should be always
String)
Synchronous
Helpful if you need to store a small amount of data
Limited size (Depends on browser)
Session Storage
If the user closes the tab, it will clear the data
You can check YDN-DB here
The key issue you have to keep in mind is you can't trust the client. If it's okay for the client to ask for any location, then it's okay for you to store the location on the client side. But you can't confirm that the value that you get back from the client side is one you have given to that client.
That's what it meant by "data manipulation" [injection is a special type of data manipulation, in that it is manipulated to include things like end quote marks if you're using it as part of a SQL query or other script.]
I highly suggest using localStorage for a few reasons:
It's supported by modern browsers,
INCLUDING IE.
You can store up to 5MB of data (10 in IE) where as a cookie is mere 4KBs
There's lots of libraries to make this easy. One of the most popular is LawnChair: http://westcoastlogic.com/lawnchair/ This will actually write to multiple places, including cookies, so that data isn't lost easily.
Also, as a note, you can't store objects with localStorage, just like you cant with cookies, however you can convert them. For example, if you want to store a Date() don't store it as new Date() store it as: '\'+Date().getTime()+'\'. Same for other objects.
Use Cookie.
How to access via javascript.
How about storing it in a cookie?
For JavaScript I recommend using jQuery, which simplifies a lot of work.
e.g. http://plugins.jquery.com/project/Cookie
Take a look at HTML5 Local Storage

How to pass array of data from one webpage to the other?

i'm trying to send three arrays of data from one .js file which is used by first webpage to the other .js file which is used by the second webpage.
the data in the first webpage is dynamically built so those three arrays are to be sent to the next webpage.
can anyone suggest some javascript code or tutorial.
please help...............
Thank you Guys. . . . ..
I'd suggest using the JSON data format. JSON is like XML except a lot easier to parse through. Some great examples can be found on Jquery's page:
http://api.jquery.com/jQuery.getJSON/
Everything you need to read the JSON feed can be found on jQuery. If you need to know how to structure a JSON feed you can read about it here:
http://www.json.org/js.html
This is really tough to do with strictly javascript and html. Here are some options:
You could store the array in a hidden form variable and post it to the destination page
If the dataset is small enough (< 4K), then you can store it in a cookie across requests.
If you are only using the most modern browsers (read: HTML5), you can use localstorage
You could encode the data and pass it in the url
In general, though, these are mostly hacks. Usually this kind of work is augmented by some type of server-side processing (perl, php, asp.net, etc) in which you have available some kind of storage across requests (i.e. Session in asp.net).
You could use the Web Storage API, and include a polyfill to port the functionality for older browsers:
http://code.google.com/p/sessionstorage/
https://gist.github.com/350433
Both of these use window.name to provide a session-like state. This may or may not be secure enough for your needs.
From there, you can use the following code for all browsers:
// Store on previous page
sessionStorage.setItem("yourArray", JSON.stringify(yourArray));
// Restore on following page
var yourArray = JSON.parse(sessionStorage.getItem("yourArray"));
EDIT: Older browsers may need the following for the above code sample. This is so the array can be serialized to a string, since sessionStorage only supports string key-value pairs:
https://github.com/douglascrockford/JSON-js
Check out jQuery.data() and friends. Cf.: http://api.jquery.com/category/data/
You may use cookie for that purpose.

Categories