A javascript variable used in multiple Web pages - javascript

Is there any way to define a variable that can be used in multiple Web pages? For example, a string variable stores a certain value in page A and that value can be accessed in page B. I know cookies can do it. Is there any other way?

window.name can also hold about 2MB of data as a string.
See: http://www.thomasfrank.se/sessionvars.html

In descending order or support: Passing it in the URI, cookies, frames, HTML5 storage
Cookies are the sensible approach. It is what they were designed for.

Related

How I get JavaScript localStorage value after redirect to another page in vue js [duplicate]

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!

How to remove localStorage key of different domain? [duplicate]

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!

Keeping a global value in the next page [duplicate]

I want to send some data from one HTML page to another. I am sending the data through the query parameters like http://localhost/project/index.html?status=exist. The problem with this method is that data remains in the URL. Is there any other method to send the data across HTML pages using JavaScript or jquery.
why don't you store your values in HTML5 storage objects such as sessionStorage or localStorage, visit HTML5 Storage Doc to get more details. Using this you can store intermediate values temporarily/permanently locally and then access your values later.
To store values for a session:
sessionStorage.setItem('label', 'value')
sessionStorage.getItem('label')
or more permanently:
localStorage.setItem('label', 'value')
localStorage.getItem('label')
So you can store (temporarily) form data between multiple pages using HTML5 storage objects which you can even retain after reload..
I know this is an old post, but figured I'd share my two cents. #Neji is correct in that you can use sessionStorage.getItem('label'), and sessionStorage.setItem('label', 'value') (although he had the setItem parameters backwards, not a big deal). I much more prefer the following, I think it's more succinct:
var val = sessionStorage.myValue
in place of getItem and
sessionStorage.myValue = 'value'
in place of setItem.
Also, it should be noted that in order to store JavaScript objects, they must be stringified to set them, and parsed to get them, like so:
sessionStorage.myObject = JSON.stringify(myObject); //will set object to the stringified myObject
var myObject = JSON.parse(sessionStorage.myObject); //will parse JSON string back to object
The reason is that sessionStorage stores everything as a string, so if you just say sessionStorage.object = myObject all you get is [object Object], which doesn't help you too much.
possibly if you want to just transfer data to be used by JavaScript then you can use Hash Tags
like this
http://localhost/project/index.html#exist
so once when you are done retriving the data show the message and change the
window.location.hash to a suitable value.. now whenever you ll refresh the page the hashtag wont be present
NOTE: when you will use this instead ot query strings the data being sent cannot be retrived/read by the server
Well, you can actually send data via JavaScript - but you should know that this is the #1 exploit source in web pages as it's XSS :)
I personally would suggest to use an HTML formular instead and modify the javascript data on the server side.
But if you want to share between two pages (I assume they are not both on localhost, because that won't make sense to share between two both-backend-driven pages) you will need to specify the CORS headers to allow the browser to send data to the whitelisted domains.
These two links might help you, it shows the example via Node backend, but you get the point how it works:
Link 1
And, of course, the CORS spec:
Link 2
~Cheers

Architecture for temporary storing of values within a javascript library

I am currently writing a javascript library that wraps a REST API provided by a third party (intended to be used on server side, but wouldn't like to limit it to). One of the actions defined by the api is 'login' which gives me a session key that I need to use on further requests. Currently, everytime I go to use this library I need to login again as there is no persistence of this session key. My question is, what is the best way to persist it throughout a session?
My first instinct was to give the library a callback that would store it and a callback that would retrieve it and the implementation can determine how that session key is persisted:
var thirdPartyApi = new ThirdPartyApi({
loginCredentials: {..},
setSessionKeyCallback: function() {},
getSessionKeyCallback: function() {}
});
thirdPartyApi.makeSomeRequest('foo');
Can you recommend the best architecture for this problem?
It seems like you want to use the REST Api in a browser. There are some factors you need to take into account, such as, navigating away from the page and coming back to it later.
You can use Web Storage to store the key. There are two types, localStorage and sessionStorage. The only difference between then is that sessionStorage is deleted when the browser window is closed, while localStorage isn't. Web Storage is supported by all modern browsers and IE8+ http://www.w3schools.com/html/html5_webstorage.asp
The localStorage object can be used as such:
localStorage.setItem("bar", foo);
var foo = localStorage.getItem("bar");
localStorage.removeItem("bar");
sessionStorage object can be used the same way.
both localStorage and sessionStorage are global objects that can be accessed from anywhere, so there is no need for any special architecture on your ThirdPartyApi object.

Can JavaScript survive a full HTTP Request Roundtrip?

Is it possible to have JavaScript (specifically, JavaScript variables and their content) survive full HTTP requests? I'd like to 'cache' / persist information client-side across page changes, without having to use hidden form fields or anything HTML related at all.
Is this possible?
Edit: Let me add a use case for what I mean.
Let's say I have a JavaScript array
called arrayOfPersons which I
loaded as part of page /HomePage,
and now it contains 1,000 objects
client-side.
Now the user switches the page and
loads an entirely new page /MyAccount into the
browser
My Goal: Still have the arrayOfPersons that I loaded on page /HomePage available after the user requested the entirely new page /MyAccount.
Hope that clarifies what I mean. Thank you!
Just to add to Nick's answer, different browsers support the idea of persistent storage in one form or another. There have been a bunch of efforts to normalize these for all browsers over the last year.
Here's one library that wraps around HTML 5's DOM Storage, Microsoft's UserData, Session Cookies and window.name (using JSON serialization as window.name can only store strings).
Here's another that focuses on window.name only (which actually works in Opera 9+, IE6+, Firefox 1.5+, Safari [3 I think).
Here's a jQuery plugin that uses a .swf (flash) file to offer the most cross-browser support (although it does support native solutions if you configure it to do so). I can't vouch for it but it should be mentioned for this jQuery-lovin' community.
Yes it is possible. Its a bit of a hack i used to maintain the page state(in client side) throughout the entire session.
Have a base page (like master), that never refreshes through out the session and it only got the iframe within it. And all your application pages will be loaded in to that frame..
Store your state info into that master page as JS objects. And you can access the master page (parent) javacript objects from your child page in a iframe. And it ll be maintained through the session in client side.
This is the simplest way. And it works pretty neat.
Found a useful one
JSOC: JavaScript Object Cache
The JSOC framework is a a pluggable,
extensible, open source client-side
caching framework for JavaScript.
JSOC offers Web developers a
straightforward way to perform common
caching techniques (add, replace,
remove, flush, etc.) inside any
JavaScript-enabled browser.
Since JSOC is a standalone JavaScript
module, incorporating JSOC into a Web
development project is a matter of
including a script reference, and
working with common caching methods.
Low-level methods are contained in the
JSOC JavaScript module so that
developers can focus on the Web
development task at hand.
Newer browsers support DOM storage which let you store arbitrary data that can persist between pages. You can also use a hidden Flash app to remember things. There are libraries like Dojo Storage which handle the detection for you, so you just save your data and it will use whatever is available.
It won't automatically save all your Javascript variables for the next page - you'll need to add an onunload handler to store what you want when the user leaves the page.
A frameset would give you a place to persist your javascript, but full page load... I think not.
Cookies might also be useful for "persisting" data, but this isn't what you asked.
if i understand you correctly, all you need is to add your own caching functions into onSubmit of all forms and onClick of all links, smth like:
var cachedpages;
$("A").onclick(function(){
url = $(this).attr('href'); // maybe hash?
if (cachedpages[url]) {
// replacing all html
} else {
$.get(url, function(data){
cachedpages[url] = data;
// replacing all html
});
}
return false;
});
One possibility is to use a frameset and keep the objects there, another to serialize them and persist the data via either of
window.name
document.cookie
location.search
document.cookie is the canonical way to store data between invocations of pages in the same domain and provides mechanisms to control access and lifetime.
If you use window.name, the data persists over the lifetime of the browser instance.
Using window.location is more tricky and you have to explicitly modify the links to send along the data (which can be easily done using event delegation).

Categories

Resources