How to pass javascript object from one page to other - javascript

I want to pass javascript object from one page to other page so anyone can tell me how to do it?
Is that possible to do so using jQuery?

Few ways
Server side postback
Have a POST form on your page and save your serialized object inside a hidden input then post it to the other page. You will be able to process that data on the server and most likely put it back somehow into the page. Either as javascript object or anything else.
Client side URL examination
Make a GET request to your other page by attaching your serialized object to URL as:
http://www.app.com/otherpage.xyz?MyObject=SerializedData
That other page can then easily parse its URL and deserialize data using Javascript.
What's in a window.name = local cross-page session
This is a special technique that's also used in a special javascript library that exposes window.name as a dictionary, so you can save many different objects into it and use it as local cross-page-session. It has some size limitations that may affect you, but check the linked page for that and test your browsers.
HTML5 local storage
HTML5 has the ability of local storage that you can use exactly for these purposes. But using it heavily depends on your browser requirements. Modern browsers support it though and data can be restored even after restarting browsers or computers...
Cookies
You can always use cookies but you may run into their limitations. These days cookies are not the best choice even though they have the ability to preserve data even longer than current window session.
Javascript object serialization
You will of course have to use some sort of a (de)serializer on your client side in some of the upper cases. Deserializers are rather easy to find (jQuery already includes a great function $.getJSON()) and are most likely part of your current javascript library already (not to even mention eval()).
But for object to JSON string serialization I'd recommend json2.js library that's also recommended by John Resig. This library uses in-browser implemented JSON (de)serialization features if they exist or uses it's own implementation when they don't. Hence recommendation.

That is only possible if the pages exist at the same time, and one page is opened from the other so that you have a reference to the other pages windows object.
If you navigate from one page to another, they don't exist at the same time, so you can't communicate like that. You would have to serialise the object into a string that you can send along in the request, for example sending JSON in the query string.
There are different ways of persisting data, like in the query string, post data, cookies, window name or HTML5 local storage, but all those methods can only persist string values, not Javascript objects.

This is possible to do, and you have a couple of options.
Local Storage
Can be added/eddited/removed at any stage and accessed across a domain. (doesn't work natively in ie6 and ie7 however there are work arounds for that)
The Window Object
I would put a massive cavet around this not being the best solution, it's not at all secure, so only use it for things that don't need to be kept private. window.name = { "json" : "object"} which is then available in the following page in the window.name property.

I believe that the only way to pass a javascript object from one page to another is to serialize it into string and pass it in url. For example if you have object
var temp = { id: 1, value: 'test' }
you may want to use JSON-js to serialize it and pass it in for example http://mysite.com/?data=serialization. Then after you load the page you need to deserialize it via for example $.parseJSON().

If your application uses sessions, you could serialize it (as per other answers) then POST it to the server where it is stored in a session variable. In the next page, you retrieve it from the session variable.

In Javascript, normally all variables only exist in a scope that is unique to that page load. They don't persist between different pages if there is a new page load.
The exceptions to this are
Cookies.
Local storage.
Cookies are truly cross-browser but are extremely limited in terms of size. You shouldn't expect to be able to store more than 4kB of cookies for a page reliably; in fact you probably shouldn't be using any more than 1kB. Cookie data slows down the loading of every page and other request, so it should be used sparingly.
There are various types of local storage available to Javascript, but the only practical cross-browser implementation of this is HTML5 webstorage which is implemented in all modern browsers (IE8+, FF, Chrome, Safari, etc), but is notably not implemented in IE6 or IE7, if that matters.
Both these approaches store a value in the user's browser which can be made to be persistent so that it can be written to and read from by pages from the same site, even between page views (and even, often, between browser sessions or computer reboots).

I wrote a library some time ago, that can store most js objects to localstorage. For example instances of your prototype classes, with references to other objects, self references included. Bare in mind that IE support is lackluster.

Related

How to keep the scope or carry vars over when changing the website with JS

I am writing a simple clickbot in JavaScript to perform repetitive tasks on a 3rd party website. It just sets input values, calls the click() method of buttons and maybe I'll have it navigate to other URLs of the same website. I initially used Firefox but got the same behaviour with Internet Explorer.
I use plain JS so far and as long as I paste in every command by myself everything works fine but here's the problem: Any time a new page is loaded (including when JS clicks a submit button) I lose all vars and functions I defined. Note that I use the web console as opposed to a <script> tag that obyiousely would be dropped when a new DOM is loaded.
Honestly, I do not entirely understand why this happens. I looked at JavaScript scope and the documentation of window.location and document.location. This site even mentioned that "In a web browser, global variables are deleted when you close the browser window (or tab), but remain available to new pages loaded into the same window." (cf. here, but that's not the point here)
I thought it might be because strict mode might be enabled by default but that would have raised an error for name = "value" instead of silently interpreting it as a local variable.
According to this answer, any var declared outside any methods should be globals that are properties of window. Changing another propertie of window (e.g. location) should not affect them - as far as my reasoning goes - but even when assigning properties myself, they disappear when I load another page.
I suppose it could be worked around if I wrote my own website that has the site I need as an iFrame so the page my script runs on would not actually be changed. But still this is strange. Can anyone explain this behaviour? Is there another (easy) way around it?
[Edit1] Thanks to same-origine policy my proposed workaround using an own website and iframe does not work. Since the whole point of my clickbot is to be started once and click through all pages on it's own, a way to carry on data (i.e. strings including JSON) is answering this question but does not solve my problem.
[Edit2] For future visitors: After recent edits, the accepted answer does provide all information I needed. Greasemonkey is the way to go if you can use addons but the combination of bookmarklets and sessionStorage stil allow for a decent bot that performes all steps between two reloads with just one user input. Another (ugly bot possibly more powerfull) approach is to open the target website and use document.body.innerHTML and the iframe workaround. That way you bypass the same-origine policy and can build your own website as needed and still access the target website.
Regarding the lifetime of a variable this SO question goes into detail, but variables don't persist across reloads.
If you're staying within the same domain (e.g. everything happens at https://example.com, so https://example.com/page1, https://example.com/page2, etc.) then you can use cookies or local storage to keep track of values.
You can't keep track of functions easily with local storage or cookies.
Cookies and local storage are not available across domains.
I would use local storage as that is easier to interface with. So instead of:
var someVar = 'hello';
Write
localStorage['someVar'] = 'hello';
Then to use the variable:
console.log(localStorage['someVar']);
Local storage has a maximum size of 10MB. Probably enough for any automation script.
If you want to persist functions across page reloads, you should use something like grease monkey to store your user scripts.

jQuery.data support across windows

I'm trying to update a web app that uses the jQuery.data() function to store information. The update involves refactoring the interface so that there are separate windows for different types of information rather than using just divs on the same page. Because of the way some plugins work the code that calls them has been moved into different windows to run in the window where they are needed. However, many of the callbacks used by these plugins use .data() to find stored information, but then code that sets the data stored by .data() is in the parent window, and it does not seem to attach the data to the DOM, it stores it somewhere attached to the window, so in the child window the callbacks can no longer find the data they are looking for.
Will it work using call(parent, DOMelement.data);? And is there possibly a tidier way of dealing with this?
Thanks in advance!
Thanks for all the suggestions. This wasn't using cookies because the information doesn't need to be stored beyond the current session. All of the interaction is done via javascript, there are no server requests until you save at the end. The windows that have to communicate are all open at the same time, hence the call() suggestion. I ended up solving this using .prop in place of .data as the syntax and functionality was almost identical. This directly associates the data with the DOM on the relevant window. $_SESSION only works when each page is requested from the server.
So, if you are trying to store information that needs to be accessed by multiple windows simultaneously or without a page refresh you can use the jQuery .prop() function to attach data to the DOM. .attr() could also work, but .prop() allows you to directly access values using . notation.
The .data functions are designed to prevent circular references but they store the information somewhere that means you can't access it without using .data which stores info separately for each context.

Uses of serialization in a web application

I'm teaching JS my self and I just been reading about objects JavaScript Objects in Detail which also discuss object serialization. So I tired to read more about that in order to understand the concept and to find a real use. So I found many tutorials on how to use JSON.stringify() and JSON.parse(), but I still can't come up with a scenario when I would need to serialize an objecct. The only one scenario I've used so far was to serialize a from with jQuery in order to sent data with .post(), but I'm not to sure if this is related.
What are the most common scenarios for serializing an object in a web application?
There are lot of scenarios, the most useful I can think of is when you want to store the data offline ( for example mobile or desktop application), you can use localStorage to store the serialized data (using JSON.stringify()) and load it back by parsing it into object (using JSON.parse()).
This offline storing of data is useful when the user don't have internet access and the user still wants to see already fetched items.
Note:
You can find more info at below references:
localStorage Reference
How to use local storage

Access URLs in the Window's History Object

Is there any way to randomly access the URLs in Javascript's History object in Safari? I'm writing an extension where I need to, on a specifically-formatted page request, capture the URL of the previous page. From what I've been able to find, the History object definition is non-standard across browsers. Safari only seems to expose its length property and the standard methods that actually move within the history. Where other implementations expose current, previous and next properties, I can't see anything that tells me Safari does the same.
I've also tried document.referrer, but that doesn't appear to get populated in this case.
I just need to display the previously accessed URL on a given page. Is there any other way to access that URL?
Thanks.
You can't really do this, at least in any white-hat way. By design. You can step the user backward and forward, but you can't see the URLs.
Less scrupulous script-writers have of course taken this as a challenge. I believe the closest they've come is to dynamically write a bunch of known comparison links to the page, and then inspect them to see if they're showing in the "visited" color state. Perhaps if you're working in a closed and predictable environment (an intranet app?), with a known set of URLs, this might be a valid approach for you. Then again, in such an environment you could deal with this on the server side with session management.

Is getting JSON data with jQuery safe?

JSON allows you to retrieve data in multiple formats from an AJAX call. For example:
$.get(sourceUrl, data, callBack, 'json');
could be used to get and parse JSON code from sourceUrl.
JSON is the simply JavaScript code used to describe data. This could be evaled by a JavaScript interpreter to get a data structure back.
It's generally a bad idea to evaluate code from remote sources. I know the JSON spec doesn't specifically allow for function declarations, but there's no reason you couldn't include one in code and have an unsafe and naive consumer compile/execute the code.
How does jQuery handle the parsing? Does it evaluate this code? What safeguards are in place to stop someone from hacking sourceUrl and distributing malicious code?
The last time I looked (late 2008) the JQuery functions get() getJSON() etc internally eval the JSon string and so are exposed to the same security issue as eval.
Therefore it is a very good idea to use a parsing function that validates the JSON string to ensure it contains no dodgy non-JSON javascript code, before using eval() in any form.
You can find such a function at https://github.com/douglascrockford/JSON-js/blob/master/json2.js.
See JSON and Broswer Security for a good discussion of this area.
In summary, using JQuery's JSON functions without parsing the input JSON (using the above linked function or similar) is not 100% safe.
NB: If this sort of parsing is still missing from getJSON (might have recently been added) it is even more important to understand this risk due to the cross domain capability, from the JQuery reference docs:
As of jQuery 1.2, you can load JSON
data located on another domain if you
specify a JSONP callback, which can be
done like so: "myurl?callback=?".
jQuery automatically replaces the ?
with the correct method name to call,
calling your specified callback.
$.getJSON() is used to execute (rather than using eval) javascript code from remote sources (using the JSONP idiom if a callback is specified). When using this method, it is totally up to you to trust the source, because they will have control to your entire page (they can even be sending cookies around).
From Douglas Crockford site about The Script Tag Hack (jsonp):
So the script can access and use
its cookies. It can access the
originating server using the user's
authorization. It can inspect the DOM
and the JavaScript global object, and
send any information it finds anywhere
in the world. The Script Tag Hack is
not secure and should be avoided.
Both IE 8 and Firefox 3.1 will have native JSON support, which will provide a safe alternative to eval(). I would expect other browsers to follow suit. I would also expect jQuery to change its implementation to use these native methods.
All browsers I know of disable cross-site requests through Ajax. That is, if your page sits on my.example.com, you can't load anything using Ajax unless its URL is also at my.example.com.
This actually can be something of a nuisance, and there are ways for an attacker to inject source in other ways, but ostensibly this restriction is in place to address exactly the concern you mention.

Categories

Resources