Persist javascript variables between GET requests? - javascript

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).

Related

Can we use the value of localStorage from other domains?

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!

Embed param with index page

I need to embed a parameter with all my pages url. Like:
index page = www.abc.com?param=value
about us page = www.abc.com/about-us.html?param=value
When i google it I found param tag. But it is child tag of Object Tag. So I don't know how to use this to address my issue.
Note: Am adding parameter to maintain my version upgrades so that browser will fetch from server whenever new updates added not fetching from cache like Google.
How to achieve that?
When i google it I found param tag. But it is child tag of Object Tag. So I don't know how to use this to address my issue.
You can't. It has nothing to do with your issue. Object parameters and query string parameters are entirely unrelated.
Am adding parameter to maintain my version upgrades so that browser will fetch from server whenever new updates added not fetching from cache like Google.
That is used when linking to resources that change infrequently and you normally want to be heavily cached, but which occasionally change in a way that would break parts of a site if not refreshed in the browser. Primarily this applies to stylesheets and JavaScript files.
For regular pages, you usually don't want such strict caching rules so you should configure your HTTP server to put appropriate cache control headers in the HTTP response for the HTML document.
For instance:
Cache-Control:max-age=3600
ETag:"44ab-51ae9454a67e2"
mnot has a good guide if you want a more in depth explanation about how to control caching.

Security issue with WebService [Get] Requests?

After reading the famous (and only) article about trying to explain why asmxs should NOTallow Get requests
so we shouldn't use : [ScriptMethod(UseHttpGet = true)] , I still I have a question :
Why ?
Web service , as its name is a service , he doesn't suppose to care if it's GET or POST :
Even if a person do a CSRF : like embedding in his malicious site :
<script type="text/javascript" src="http://contoso.com/StockService/Stock.asmx/GetQuotes?symbol=msft" />
so what ?
Via asmx POV - it is just a normal request.
Can someone please spot for me the problem with example ?
edit
there are many problems solved with new browsers.
this link shows some other methods which should be tested in new browsers.
JSON hijacking is briefly explained in this article.
Let's suppose that you have a web service that returns a list of credit card numbers to the currently authenticated user:
[{"id":"1001","ccnum":"4111111111111111","balance":"2345.15"},
{"id":"1002","ccnum":"5555555555554444","balance":"10345.00"},
{"id":"1003","ccnum":"5105105105105100","balance":"6250.50"}]
Here's how the attack could be performed:
Get an authenticated user to visit a malicious page.
The malicious page will try and access sensitive data from the application that the user is logged into. This can be done by embedding a script tag in an HTML page since the same-origin policy does not apply to script tags. <script src="http://<json site>/json_server.php"></script>. The browser will make a GET request to json_server.php and any authentication cookies of the user will be sent along with the request.
At this point while the malicious site has executed the script it does not have access to any sensitive data. Getting access to the data can be achieved by using an object prototype setter. In the code below an object prototypes property is being bound to the defined function when an attempt is being made to set the "ccnum" property.
Object.prototype.__defineSetter__('ccnum',function(obj) {
secrets = secrets.concat(" ", obj);
});
At this point the malicious site has successfully hijacked the sensitive financial data (ccnum) returned by json_server.php.
There are also other forms of JSON hijacking techniques which do not rely on the browser support for the __defineSetter__ function. That's just one way to conduct the attack but there are many others as described in this article such as Array constructor clobbering, UTF-7, ES5 functionality.
For this reason, GET requests returning JSON are disabled by default in ASP.NET.
Well if you follow the article that is then linked in the one you provided which can be found here: http://ajax.asp.net/docs/overview/AsynchronousLayerOverview.aspx, you can then read on and the only reason it specifically specifies is this:
GET requests are not recommended for method calls that modify data on
the server or that expose critical information. In GET requests, the
message is encoded by the browser into the URL and is therefore an
easier target for tampering. For both GET and POST requests, you
should follow security guidelines to protect sensitive data.

Performing JS methods on a URL submitted by the user?

I haven't found an answer to this, and since I'm pretty new to JS, I don't know if it's even possible.
I have a regular HTML form, where the only field is a user types in a URL (any URL) and clicks submit.
The URL will "be sent" to JS code that stores this URL in some variable, I guess. Basically, I need to be able to call getElementsByTagName() on any URL submitted by the user.
My point is to count up the number of times a URL contains a specified element, which I do know how to do :)
How do I interpret a URL submitted through a form by someone and then take that URL and be able to perform methods (such as getElementsById) on it? I want to return the count of the number of elements to the user.
Any ideas? Can this all be done in JS? Is this possible?
When you say "URL," I assume you are talking about the actual webpage and not the url string. In other words, you want to load the entire DOM into a javascript variable and then parse it with getElementsByTagName(), etc. Javascript cannot load this webpage due to the Same Origin Policy, unless users can only submit pages that are on the same domain as your site. If that was the case, you could use a frame. Otherwise, JS can't do it without Jsonp, which isn't going to work in this case.
However, all is not lost. You can have your JS make an asynchronous request (ajax) to your own server. Your server scripting language /can/ get the entire DOM of the webpage (e.g. PHP can do this with cURL). Then it can send the entire string back to JS as xml that can be parsed. Good luck.
You can't really do that from the client (the web browser) with nothing but Javascript, because security rules will prevent your page from fetching and examining content from a different domain. You'll need to send the URL to a server and have it do the work.

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/

Categories