Can we use the value of localStorage from other domains? - javascript

I am storing a value in local storage in one domain. Can I retrieve that value from another domain if I am accessing both domain from same browser?

No, you can't use the local storage of one domain to other domain.
Local Storage is domain based. You can’t read or write from localstorage that’s on different domain even on it's subdomain.
you can use it via Iframe on your subdomain.
Please go through this article Cross-Domain LocalStorage for detailed explanation.
Hope it'll help. :)

Yes, you can use this javascript library.
Bifrost-cors size: <2KB
It's very simple to use, you just need to invoke method.
// In www.exampleA.com site:
var bifrostCors = new bifrostCors("http://exampleB.com/", false)
// In www.exampleB.com site
var bifrostCors = new bifrostCors("http://exampleA.com/", false)
bifrostCors.getLocalStorage("local-storage-key-of-what-you-want")
Actually this lib render the iframe (hidden) and uses window.postMessage to communicate with two different contexts (domain).
You can also implement by yourself but this lib is very very light < 2Kb.
Also not only you can access localStorage you have feature also like.
Get/Set Cookie
Bi-directional message thread
Run JS expression from one domain to other
DOM Manipulation from one domain to other domain ( Iframe )

You may want to take a look at this blog post. It seem to suggest that you can attempt to use an iframe as a workaround to access local storage from another domain.
Disclaimer: I haven't tried it before but it seems interesting. Let me know if it works!

Related

access web sql database between 2 html5 pages

I am new to html5 and js,if this is a very simple question, please forgive my ignorance.
But can someone please help me in figuring a solution for my case:
I have created some static html5 pages and also a offline database from my js code which is accessed across all the html5 pages.
Now i am trying to update the database from one page and want the updated database reflection across all the html5 pages.
Thanks in advance.
As you said it is offline db, store the values in some global variable before storing it in database. And in all other pages , rely on that global variable.So , if you have some data updated in page1, store it in some global variable also. And use that variable in all other pages.
To access the offline databases from several different pages, please make sure all your pages are in the same domain.
Create a fresh connection to the database on all your pages.
var db_conn = window.openDatabase( _ID_DATABASE_NAME, _ID_DATABASE_VERSION, _ID_DATABASE_DESC, _ID_DATABASE_SIZE );
All the parameters passed to the function should remain same.
In case the values you are trying to access are only a few name value pairs, try to use the concept of local storages. Following are the setter getter methods accessible across pages.
window.localStorage.setItem( 'myFirstLocalStorage_Name', 'myFirstLocalStorage_Value' );
var ls_value = window.localStorage.getItem( 'myFirstLocalStorage_Name' );
Hope you'll be able to get your values across pages.
The domain of both pages is needed to be same.
and w3c says
User agents may restrict access to the database objects to scripts
originating at the domain of the top-level document of the browsing
context, for instance denying access to the API for pages from other
domains running in iframes.

Accessing the url of a remote window in Javascript

I open a new window to a Google docs presentation using the method window.open :
NewWindow = window.open("https://docs.google.com/presentation/d/1Qs9......");
I want to retrieve that url in order to know of it has changed (each slide of the presentation has a different url and i want to see if the user changed slides), using NewWindow.location.href
All i get is an undefined value. I can change href though
NewWindow.location.href ="http://www.google.com"; //works
I've read that if you are not in the same domain, you are not allowed to access the href or any other properties on the remote window.
Isn't there any other way to do it?
Thanks in advance.
There is a workaround but not in JavaScript.
The standard solution is to map the documents into your own domain using a proxy server that runs hidden under some URL of your own domain.
That way, you can access the documents via https://your.doma.in/google/presentation/...
A word of warning: If you make a mistake with configuring the proxy, crackers can abuse it to do nasty things (like trying to hack Google or send spam; the police will come knocking on your door).

how can I POST cookies to a different link?

Is there any way to POST all the cookies(cookie name , value and expire time) available for a specific domain (e.g .example.com) using javascript ? . I own the domain that I need the cookies to POST from but I want to post them to a different domain (e.g example2.com). After the cookies are POST ed I also need to redirect the client to a specific link so I think some ajax may be required
Note : I do not need to read/write cookies on different domain. I simply need to send/transport the cookies names/values/exp of the current domain to a different domain as HTTP POST values
You can access the cookies using document.cookie. However, this only gives you the name and value - there's no way (that I know of) to get the expiration date of a cookie. It contains a string with all the cookies, in a name1=value1; name2=value2; name3=value3; format.
Sending it as a POST request to another domain can be done with cross-domain XHR, but if you don't need to read the HTTP response of the request, submitting a form should be enough. Simply create an invisible <form> with its method attribute set to "post", the action attribute set to the URL on the other domain and the target attribute set to the id of an invisible iframe, add the cookies as an <input>, and submit the form.
<iframe id="foo" style="display: none"></iframe>
<form id="bar" method="post" target="foo"
action="http://www.someotherdomain.com/handle_cookies.php">
<input id="cookies" type="hidden" name="cookies" />
</form>
<script type="text/javascript">
document.getElementById('cookies').value = document.cookie;
document.getElementById('bar').submit();
</script>
Its probably better to create the <iframe> and <form> dynamically, using JavaScript, instead of having it written in the HTML, but I'm too lazy to write that at 2:30AM, sorry :P
note: If the first domain is accessed on SSL, make sure the connection to the other domain is also over SSL, otherwise you'll be transmitting secured cookies over HTTP as plain text. You can remove the scheme part from the URL of the other domain (e.g. //www.someotherdomain.com/handle_cookies.php instead of http://www.someotherdomain.com/handle_cookies.php), making it use the same scheme as the one used where the cookies are sent from. I highly recommend doing that.
The link describes a method that comes close to the requirement. But it uses the window.name property instead of cookies to send data.
Google cache copy, because the original link seized to work for a while.
Using window.name transport for cross-site POST scripting
I think due to security reasons you can't read/write a cookie for a different domain. You can apply a specific path for the cookie to be available to such as a specific folder outside of your root. I think the way the browsers work is they find cookies for the site they are accessing at the moment, and use them accordingly. But allowing for cookies to be cross domains would open up to many threats. I think, if you really want though I can't promise something like this working fully.
If you build a script on the other domain that will write a cookie based on a trigger and then you use something like PHP cURL to bring the page into the domain your working with at the moment you may be able to invoke a cookie from the other domain. This is pure theory though not something I have tested. The idea is since you own both domains its assumed you also have access to both hosting servers. So with that you need something on both ends to work with one another to do what you want, rather then hope for a one sided solution.
Reference: http://www.quirksmode.org/js/cookies.html

How do I preserve variable values between HTML files?

Let's say I have a page that refers to a .js file. In that file I have the following code that sets the value of a variable:
var foo;
function bar()
{
foo = //some value generated by some type of user input
}
bar();
Now I'd like to be able to navigate to another page that refers to the same script, and have this variable retain the value set by bar(). What's the best way to transport the value of this variable, assuming the script will be running anew once I arrive on the next page?
You can use cookies.
Cookies were originally invented by
Netscape to give 'memory' to web
servers and browsers. The HTTP
protocol, which arranges for the
transfer of web pages to your browser
and browser requests for pages to
servers, is state-less, which means
that once the server has sent a page
to a browser requesting it, it doesn't
remember a thing about it. So if you
come to the same web page a second,
third, hundredth or millionth time,
the server once again considers it the
very first time you ever came there.
This can be annoying in a number of
ways. The server cannot remember if
you identified yourself when you want
to access protected pages, it cannot
remember your user preferences, it
cannot remember anything. As soon as
personalization was invented, this
became a major problem.
Cookies were invented to solve this
problem. There are other ways to solve
it, but cookies are easy to maintain
and very versatile.
See: http://www.quirksmode.org/js/cookies.html
You can pass the value in the query string.
When the user navigate to the other page append the value to the query string and load it in the next.
Another option is jStorage. jStorage is probably better used for cached data and lossy user preferences (e.g. saved username in a login form), as it doesn't have full browser support (but IE6+ and most other common browsers support it) and cannot be relied upon (like cookies).
You can use YUI's Cookie Library http://developer.yahoo.com/yui/cookie/

Persist javascript variables between GET requests?

ASP .NET is allowed
Storing the values in hidden input fields is allowed
Query String is not allowed
POST request is not allowed
It is possible to store JS variables between GET requests ?
I want to reinitialize them on the client using ClientScript.RegisterStartupScript
Can I use cookies for this ?
Are there other posibilities?
Where cookies are stored when Request is made ?
Can I use cookies for this ?
Yes, see this tutorial on using cookies in Javascript.
Are there other posibilities?
If you are not allowed to append anything the URL of your requests, I can't come up with any.
Where cookies are stored when Request is made ?
In the HTTP request header. The aforementioned tutorial will tell you how to read their values from Javascript. On the server side with ASP.Net, you can read cookie values using Request.Cookie["cookieName"] which returns an instance of HttpCookie.
I wouldn't highly recommend this, but the other option is to alter the window.name property.
You can save some minor bits of data here, then retrieve them on the next page load.
Pros:
Quick-n-dirty, but works
Cons:
Messes up any window references for popups/child iframes
Since its a "hack", browser vendors may break this "feature" in the future
Of course if you can exclude all the old browsers, then use Global/Client Session Storage!
At the moment using cookies is your best bet. You can serialize the JavaScript objects to strings, and unserialize them back into objects later. A good choice format is JSON, since it is a subset of JavaScript.
There is also storing objects in Flash.
Storing in Google Gears.
DomStorage
See this library that has an interface to each:
http://pablotron.org/?cid=1557
If you are in control of all aspects of the page, then you can also wrap the page in a top level frame. Then only refresh the child frame. You can then store content in the parent frame.
You can see this used in sites like GMail, and others where the only thing that changes in the URL is outside the #.
You don't even have to change the URL, that part is just put in for Human Friendly URLs. (So you can actually copy and paste URLs as is).

Categories