Can JavaScript survive a full HTTP Request Roundtrip? - javascript

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

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!

Page Load alternative in a Pure HTML AJAX Website

I am working on a pure HTML website, all pages are HTML with no relation to any server side code.
Basically every request to the server is made using AJAX, I send data from forms, I process this data in Handlers, then I return a JSON string that will be processed back on the client side.
Let's say the page is loaded with parameters in the URL, something like question.html?id=1. Earlier, I used to read this query string on Page Load method, then read data from the database and so on...
Now, since its pure HTML pages, I'm trying to think of an approach that will allow me to do the same, I have an idea but its 99% a bad idea.
The idea is to read URL parameters using JS (after the page has loaded), and then make an AJAX request, and then fetch the data and show them on the page. I know that instead of having 1 request to the server (Web Forms), we are now having 2 Requests, the first request to get the page, and the second request is the AJAX request. And of course this has lots of delays, since the page will be loaded at the beginning without the actual data that I need inside it.
Is my goal impossible or there's a mature approach out there?
Is my goal impossible or there's a mature approach out there?
Lately there are a good handful of JavaScript frameworks designed around this very concept ("single page app") of having a page load up without any data pre-loaded in it, and accessing all of the data over AJAX. Some examples of such frameworks are AngularJS, Backbone.js, Ember.js, and Knockout. So no, this is not at all impossible. I recommend learning about these frameworks and others to find one that seems right for the site you are making.
The idea is to read URL parameters using JS (after the page has loaded), and then make an AJAX request, and then fetch the data and show them on the page.
This sounds like a fine idea.
Here is an example of how you can use JavaScript to extract the query parameters from the current page's URL.
I know that instead of having 1 request to the server (Web Forms), we are now having 2 Requests, the first request to get the page, and the second request is the AJAX request. And of course this has lots of delays, since the page will be loaded at the beginning without the actual data that I need inside it.
Here is why you should not worry about this:
A user's browser will generally cache the HTML file and associated JavaScript files, so the second time they visit your site, the browser will send requests to check whether the files have been modified. If not, the server will send back a short message simply saying that they have not been modified and the files will not need to be transmitted again.
The AJAX response will only contain the data that the page needs and none of the markup. So retrieving a page generated on the server would involve more data transfer than an approach that combines a cacheable .html file and an AJAX request.
So the total load time should be less even if you make two requests instead of one. If you are concerned that the user will see a page with no content while the AJAX data is loading, you can (a) have the page be completely blank while the data is loading (as long as it's not too slow, this should not be a problem), or (b) Throw up a splash screen to tell the user that the page is loading. Again, users should generally not have a problem with a small amount of load time at the beginning if the page is speedy after that.
I think you are overthinking it. I'd bet that the combined two calls that you are worried about are going to run in roughly the same amount of time as the single webforms page_load would if you coded otherwise - only difference now being that the initial page load is going to be really fast (because you are only loading a lightweight, html/css/images page with no slowdown for running any server code.
Common solution would be to then have a 'spinner' or some sort (an animated GIF) that gives the user an visual indication that the page isn't done loading while your ajax calls wait to complete.
Watch a typical page load done from almost any major website in any language, you are going to see many, many requests that make up a single page being loaded, wether it be pulling css/images from a CDN, js from a CDN, loading google analytics, advertisements from ad networks etc. Trying to get 100% of your page to load in a single call is not really a goal you should be worried about.
I don't think the 2-requests is a "bad idea" at all. In fact there is no other solution if you want to use only static HTML + AJAX (that is the moderm approach to web development since this allow to reuse AJAX request for other non-HTML clients like Android or iOS native apps). Also performance is very relative. If your client can cache the first static HTML it will be much faster compared to server-generated approach even if two requests are needed. Just use a network profiler to convince yourself.
What you can do if you don't want the user to notice any lag in the GUI is to use a generic script that shows a popup hiding/blocking all the full window (maybe with a "please wait") until the second request with the AJAX is received and a "data-received" (or similar) event is triggered in the AJAX callback.
EDIT:
I think that probably what you need is to convert your website into a webapp using a manifest to list "cacheable" static content. Then query your server only for dynamic (AJAX) data:
http://diveintohtml5.info/offline.html
(IE 10+ also support Webapp manifests)
Moderm browsers will read the manifest to know whether they need to reload static content or not. Using a webapp manifest will also allow to integrate your web site within the OS. For example, on Android it will be listed in the recent-task list (otherwise only your browser, not your app is shown) and the user can add a shorcut to the desktop.
So, you have static HTMLs and user server side code only in handlers? Why you can't have one ASP .Net page (generated on server side) to load initial data and all other data will be processed using AJAX requests?
if its possible to use any backed logic to determine what to load on server side, that will be easy to get the data.
say for example if you to load json a int he page cc.php by calling the page cc.php?json=a, you can determine from the PHP code to put a json into the page it self and use as object in your HTML page
if you are using query string to read and determine, what to load you have to make two calls.
The primary thing you appear to want is what is known as a router.
Since you seem to want to keep things fairly bare metal, the traditional answer would be Backbone.js. If you want even faster and leaner then the optimised Backbone fork ExoSkeleton might be just the ticket but it doesn't have the following that Backbone proper has. Certainly better than cooking your own thing.
There are some fine frameworks around, like Ember and Angular which have large user bases. I've been using Ember recently for a fairly complex application as it has a very sophisticated router, but based on my experiences I'm more aligned with the architecture available today in React/Flux (not just React but the architectural pattern of Flux).
React/Flux with one of the add-on router components will take you very far (Facebook/Instrgram) and in my view offers a superior architecture for web applications than traditional MVC; it is currently the fastest framework for updating the DOM and also allows isomorphic applications (run on both client and server). This represents the so called "holy grail" of web apps as it sends the initial rendered page from the server and avoids any delays due to framework loading, subsequent interactions then use ajax.
Above all, checkout some of the frameworks and find what works best for you. You may find some value comparing framework implementations over at TodoMVC but in my view the Todo app is far too simple and contrived to really show how the different frameworks shine.
My own evolution has been jQuery -> Backbone -> Backbone + Marionette -> Ember -> React/Flux so don't expect to get a good handle on what matters most to you until you have used a few frameworks in anger.
The main issue is from a UX / UI point of view.
Once you get your data from the server (in Ajax) after the page has been loaded - you'll get a "flickering" behavior, once the data is injected into the page.
You can solve this by presenting the page only after the data has arrived, OR use a pre-loader of some kind - to let the user know that the page is still getting its data, but then you'll have a performance issue as you already mentioned.
The ideal solution in this case is to get the "basic" data that the page needs (on the first request to the server), and manipulate it via the client - thus ease-in the "flickering" behavior.
It's the consideration between performance and "flickering" / pre-loading indication.
The most popular library for this SPA (Single Page Application) page - is angularJS
If I understand your inquiry correctly. You might want to look more about:
1) window.location.hash
Instead of using the "?", you can make use of the "#" to manipulate your page based on query string.
Reference: How to change the querystring on the same page without postback
2) hashchange event
This event fires whenever there's a changed in the fragment/hash("#") of the url. Also, you might want to track the hash to compare between the previous hash value and the current hash value.
e.g.
$(window).on('hashchange', function () {
//your manipulation for query string goes here...
prevHash = location.hash;
});
var prevHash = location.hash; //For tracking the previous hash.
Reference: On - window.location.hash - Change?
3) For client-side entry-point or similar to server-side PageLoad, you may make use of this,
e.g.
/* Appends a method - to be called after the page(from server) has been loaded. */
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function () {
if (oldonload) {
oldonload();
}
func();
}
}
}
function YourPage_PageLoad()
{
//your code goes here...
}
//Client entry-point
addLoadEvent(YourPage_PageLoad);
Since you're doing pure ajax, the benefit of this technique is you would be able to easily handle the previous/next button click events from the browser and present the proper data/page to the user.
I would prefer AngularJS. This will be a good technology and you can do pagination with one HTML. So i think this will be good framework for you as your using static content.
In AngularJS MVC concept is there please read the AngularJS Tutorial. So this framework will be worth for your new project. Happy coding

Persist Local UIWebView Values

*EDIT*
I've done more research and it looks like cookies may also be the answer. I suppose I would add a button to the form inside the embedded html that calls a function to create a cookie for the values. Then I could access this cookie through obj-c using the stringByEvaluatingJavaScriptFromString method. Of course then you run into the issue of expiration, multiple copies of the form not being allowed, etc. So it is a trade-off of features. I'm going to stick with the window.location route because I can store this in a DB and then the user can create another instance of the same form
*EDIT*
I've done some research and I have a vague idea how to accomplish this, but I was curious if there was a better method.
I have a local copy of an html form loading in a UIWebView on this iPad app I am developing. The forms are submitted server-side through xml and parsed there for DB storage, but unfortunately they are pretty lengthy. So I want to let the user save the form in its current state (maybe they only fill it out halfway), and then return to it later.
What I am thinking is that I will have to write some javascript to parse the radio buttons and checkboxes in the form, then pass this data through the window.location trick to the obj-c code. But this is VERY lengthy, and the strings being passed back and forth between JS and Obj-C will be very long. Is there any other way to grab the values of these checkboxes/radio buttons and pass them to the obj-c side to be repopulated later?
How about going via a file? Save the settings/data to a file in JS and access that file in Objective-C land. But I guess you've already thought of this.
But at the end of the day the data has to be passed back and forth regardless of how you do it. Doing it via the window.location trick will be the fastest, and provided there are no limitations imposed by the OS itself is there any reason not to do it this way?
You could encode the data into a blob to make it easier to pass around.
But on the other hand doing it by file route may however be useful if you want the settings to persist if your app gets terminated.
Also you could actually submit the form data but intercept it in Objective-C before it gets sent by using a NSURLProtocol derived class. THe NSURLProtocol class could allow the submission to proceed if it knows the data is complete. But I don't see any point in doing this if window.location doesn't have a size limit.

History.pushState and page refresh

I started looking at HTML5 new history API
However, I have one question. How can one handles the page refresh?
For example a user clicks a link, which is handled by a js function, which
asynchronously loads the content of the page
changes the URL with history.pushState()
The the user refreshes the page, but the URL of course does not exist on the server
How do you handle situations like this? With the hash solution there was no issue there
Thanks
This does require the server-side support. The ideal use of .pushState is to allow URLs from JavaScript applications to be handled intelligently by the server.
This could be either by re-serving the same JavaScript application, and letting it inspect window.location, or by rendering the content at that URL on the server as you would for a normal web application. The specifics obviously vary depending on what you're doing.
You need to perform server side redirection for copy and pasted fake URLs
It all depends on what server side technology you're using. There is no JavaScript way but writing a crazy function in your 404 page that redirect user based on incoming URL that is not a good solution.
The the user refreshes the page, but the URL of course does not exist
on the server
What do you mean by this? I have a feeling your assumption is wrong.
Actually yes, the point is it is the developer who should provide (serverside or clientside) implementation of url-to-pagestate correspondence.
If, once again, I've get the question right.
If you are using ASP.NET MVC on your server, you can add the following to your RegisterRoutes function:
routes.MapRoute(
name: "Default",
url: "{*url}",
defaults: new { controller = "Home", action = "Index" }
);
This will send all requests to Index action of your HomeController and your UI will handle the actual route.
For people looking for a JS-only solution, use the popstate event on window. Please see MDN - popstate for full details, but essentially this event is passed the state object you gave to pushState or replaceState. You can access this object like event.state and use it's data to determine what to do, ie show an AJAX portion of a page.
I'm not sure if this was unavailable in 2011 but this is available in all modern browsers (IE10+), now.

Could a page display diferrent content if the URL hash changes?

How could a page display different content based on the URL hash?
I'm not talking about the browser scrolling down to display the anchored section, but something like JavaScript reacting to that hash and loading different content via AJAX.
Is this common or even probable?
Oh yes - it's becoming a common pattern to handle page-state-to-URL persistence when content is AJAX driven.
Javascript can access this value via window.location.hash. Once that's done, you can perform any actions based on the value of that hash
Show/hide nodes
Makes other AJAX calls
Change page titles or colors
Swap images
etc
Really, any DHTML effect.
This is occasionally done. Youtube uses hashes to link to specific timestamps within a video.
EDIT: I had assumed that you might have an issue where if the user goes up and manually edits the hash in the address bar, the page doesn't reload and even javascript will not know that it changed. I was wrong. I tried it on Youtube it works.
I just built a system to do this a few weeks ago
depeding on the browser you need to detect the hash, heres how to do that
// test all possible places hash could be on different browsers
if(window.location.hash){
hash = window.location.hash;
} else if (document.location.hash){
hash = document.location.hash;
} else if (location.hash){
hash = location.hash;
}
// some browsers start the hash with #, remove it for consistency
if(hash.substring(0,1) == '#'){
hash = hash.substring(1,hash.length);
}
Then handle the value of the hash variable to trigger page changes as you please.
for example:
http://www.example.com#pageA
if(hash = 'pageA'){
document.getElementById('mainContentDiv').innerHTML = '<p> content for the page displayed when the hash sais pageA</p>';
}
Sammy is a javascript library that does just this.
As JavaScript has access to the URL-string it could of course act differently on the contents of the url.
I've occassionally seen something like this but I don't think that this is a good way to react unless in very specific uses.
One of the uses I remember was TiddlyWiki using the after-portion of the hash to set preferences for the page rendering and such.
It is fairly common among AJAX-heavy applications (think Gmail) to be able to have all the AJAXy stuff while still making it possible for you to bookmark a particular page or link someone to a particular page. If they didn't do this, it would be considered bad for usability. It is fairly easy to get the URL hash by doing window.location.hash - so you can then have a switch-like statement on page load to execute a particular set of Javascript functions if a hash is present.
Some jQuery plugins that achieve this functionality: history/remote, history.
The answer for this question will be more or less the same as my answers for these questions:
How to show Ajax requests in URL?
How does Gmail handle back/forward in rich JavaScript?
In summary, two projects that you'll probably want to look at which explain the whole hashchange process and using it with ajax are:
jQuery History (using hashes to manage your pages state and bind to changes to update your page).
jQuery Ajaxy (ajax extension for jQuery History, to allow for complete ajax websites while being completely unobtrusive and gracefully degradable).

Categories

Resources