Search Results

Search found 103 results on 5 pages for 'localstorage'.

Page 2/5 | < Previous Page | 1 2 3 4 5  | Next Page >

  • LocalStorage storing multiple div hides

    - by Jesse Toxik
    I am using a simple code to hide multiple divs if the link to hide them is clicked. On one of them I have local storage set-up to remember of the div is hidden or not. The thing is this. How can I write a code to make local storage remember the hidden state of multiple divs WITHOUT having to put localstorage.setItem for each individual div. Is it possible to store an array with the div ids and their display set to true or false to decide if the page should show them or not? **********EDITED************ function ShowHide(id) { if(document.getElementById(id).style.display = '') { document.getElementById(id).style.display = 'none'; } else if (document.getElementById(id).style.display = 'none') { document.getElementById(id).style.display = ''; }

    Read the article

  • Sencha 2 : Sync models with hasMany associations in LocalStorage

    - by Alytrem
    After hours and hours trying to do this, I need your help. I have to models : Project and Task. A project hasMany tasks and a task belong to a project. Everyting works well if you don't use a store to save these models. I want to save both tasks and projects in two stores (TaskStore and ProjectStore). These stores use a LocalStorage proxy. I tried many things, and the most logical is : Ext.define('MyApp.model.Task', { extend: 'Ext.data.Model', config: { fields: [ { name: 'name', type: 'string' }, { dateFormat: 'd/m/Y g:i', name: 'start', type: 'date' }, { dateFormat: 'd/m/Y g:i', name: 'end', type: 'date' }, { name: 'status', type: 'string' } ], belongsTo: { model: 'MyApp.model.Project' } } }); Ext.define('MyApp.model.Project', { extend: 'Ext.data.Model', alias: 'model.Project', config: { hasMany: { associationKey: 'tasks', model: 'MyApp.model.Task', autoLoad: true, foreignKey: 'project_id', name: 'tasks', store: {storeId: "TaskStore"} }, fields: [ { name: 'name', type: 'string' }, { dateFormat: 'd/m/Y', name: 'start', type: 'date' }, { dateFormat: 'd/m/Y', name: 'end', type: 'date' } ] } }); This is my "main" : var project = Ext.create("MyApp.model.Project", {name: "mojo", start: "17/03/2011", end: "17/03/2012", status: "termine"}); var task = Ext.create("MyApp.model.Task", {name: "todo", start: "17/03/2011 10:00", end: "17/03/2012 19:00", status: "termine"}); project.tasks().add(task); Ext.getStore("ProjectStore").add(project); The project is added to the store, but task is not. Why ?!

    Read the article

  • Do all the HTML5 storage systems work together ?

    - by azera
    While there are a lot of good stuff about html5, one thing I don't get is the redondant storage mechanism, first there is localstorage and sessionstorage, which are key value stores, one is for one instance of the app ("one tab"), and the other works for all the instances of that application so they can share data. Both are saved when you close your browser and have a limited size (usually 5MB), that's great and everything would be nice if we stopped there. But then there is the "Web SQL Database", which has the same security system as the localstorage, the same size limit, the same everything except it works like/is sqlite, with tables and sql syntax and all of that. And the bummer is, they don't work on the same data at all ! This is not two way to access your data, this is really two storage for every html 5 app out there (not created by default yes, but still you see my point). What I would like to know is, is there a reason for both of this mechanisms to exist at the same time ? Or did they just look at sql and nosql movement to pick the best then went "screw it let's add both !" ? Why not implement local/session storage as a table inside web sql db ?

    Read the article

  • Get URL and save it | Chrome Extension

    - by Jamie
    Basically on my window (when you click the icon) it should open and show the URL of the tab and next to it I want it to say "Save", it will save it to the localStorage, and to be displayed below into the saved links area. Like this:

    Read the article

  • How to store a 250mb database in an Offline Web App

    - by Couto
    Ok, maybe i'm not seeing the whole picture or something, but i kinda need a brainstorm. So the purpose is to make a webapp (HTML5, CSS, Javascript) that has to search on a 250mb database without any internet connection, so.. yes the database has to be on the client side. The hard part here is, this App has to work on an iPod or iPhone without internet connection. (An initial connection to download the App is ok), LocalStorage has a 5mb limit, couchDB would be great since they have an webapp easily accessed by Javascript (privacy concerns don't matter at this point), so i'm pretty much out of ideas.... Does anyone see an alternative, or solution for the purpose?

    Read the article

  • How to bind to localStorage change event using jQuery for all browsers?

    - by David Glenn
    How do I bind a function to the HTML5 localStorage change event using jQuery? $(function () { $(window).bind('storage', function (e) { alert('storage changed'); }); localStorage.setItem('a', 'test'); }); I've tried the above but the alert is not showing. Update: It works in Firefox 3.6 but it doesn't work in Chrome 8 or IE 8 so the question should be more 'How to bind to localStorage change event using jQuery for all browsers?'

    Read the article

  • sorting dynamic table created by form inputs [migrated]

    - by mille
    i am having problems with sorting can someone help to sort this table not just by its form entry id but onclick with some other columns i tried a lot of plugins but cant get anything to work and i dont know what to do i am new at this i sorry for my english thanks. here is the js: var Animals ={ index: window.localStorage.getItem("Animals:index"), $table: document.getElementById("animals-table"), $form: document.getElementById("animals-form"), $button_save: document.getElementById("animals-save"), $button_discard: document.getElementById("animals-discard"), init: function() { if (!Animals.index) { window.localStorage.setItem("Animals:index", Animals.index = 1); } Animals.$form.reset(); Animals.$button_discard.addEventListener("click", function(event) { Animals.$form.reset(); Animals.$form.id_entry.value = 0; }, true); Animals.$form.addEventListener("submit", function(event) { var entry = { id: parseInt(this.id_entry.value), animal_id:this.animal_id.value, animal_name: this.animal_name.value, animal_type: this.animal_type.value, bday: this.bday.value, animal_sex: this.animal_sex.value, mother_name: this.mother_name.value, farm_name: this.farm_name.value, money: this.money.value, weight: this.weight.value, purchase_partner: this.purchase_partner.value }; if (entry.id === 0) { Animals.storeAdd(entry); Animals.tableAdd(entry); } else { // edit Animals.storeEdit(entry); Animals.tableEdit(entry); } this.reset(); this.id_entry.value = 0; event.preventDefault(); }, true); if (window.localStorage.length - 1) { var animals_list = [], i, key; for (i = 0; i < window.localStorage.length; i++) { key = window.localStorage.key(i); if (/Animals:\d+/.test(key)) { animals_list.push(JSON.parse(window.localStorage.getItem(key))); } } if (animals_list.length) { animals_list.sort(function(a, b) {return a.id < b.id ? -1 : (a.id > b.id ? 1 : 0);}) .forEach(Animals.tableAdd);} Animals.$table.addEventListener("click", function(event) { var op = event.target.getAttribute("data-op"); if (/edit|remove/.test(op)) { var entry = JSON.parse(window.localStorage.getItem("Animals:"+ event.target.getAttribute("data- id"))); if (op == "edit") { Animals.$form.id_entry.value = entry.id; Animals.$form.animal_id.value = entry.animal_id; Animals.$form.animal_name.value = entry.animal_name; Animals.$form.animal_type.value = entry.animal_type; Animals.$form.bday.value = entry.bday; Animals.$form.animal_sex.value = entry.animal_sex; Animals.$form.mother_name.value = entry.mother_name; Animals.$form.farm_name.value = entry.farm_name; Animals.$form.money.value = entry.money; Animals.$form.weight.value = entry.weight; Animals.$form.purchase_partner.value = entry.purchase_partner; } else if (op == "remove") { if (confirm('Are you sure you want to remove this animal from your list?' )) { Animals.storeRemove(entry); Animals.tableRemove(entry); } } event.preventDefault(); } }, true); }, storeAdd: function(entry) { entry.id = Animals.index; window.localStorage.setItem("Animals:index", ++Animals.index); window.localStorage.setItem("Animals:"+ entry.id, JSON.stringify(entry)); }, storeEdit: function(entry) { window.localStorage.setItem("Animals:"+ entry.id, JSON.stringify(entry)); }, storeRemove: function(entry) { window.localStorage.removeItem("Animals:"+ entry.id); }, tableAdd: function(entry) { var $tr = document.createElement("tr"), $td, key; for (key in entry) { if (entry.hasOwnProperty(key)) { $td = document.createElement("td"); $td.appendChild(document.createTextNode(entry[key])); $tr.appendChild($td); } } $td = document.createElement("td"); $td.innerHTML = '<a data-op="edit" data-id="'+ entry.id +'">Edit</a> | <a data-op="remove" data-id="'+ entry.id +'">Remove</a>'; $tr.appendChild($td); $tr.setAttribute("id", "entry-"+ entry.id); Animals.$table.appendChild($tr); }, tableEdit: function(entry) { var $tr = document.getElementById("entry-"+ entry.id), $td, key; $tr.innerHTML = ""; for (key in entry) { if (entry.hasOwnProperty(key)) { $td = document.createElement("td"); $td.appendChild(document.createTextNode(entry[key])); $tr.appendChild($td); } } $td = document.createElement("td"); $td.innerHTML = '<a data-op="edit" data-id="'+ entry.id +'">Edit</a> | <a data-op="remove" data-id="'+ entry.id +'">Remove</a>'; $tr.appendChild($td); }, tableRemove: function(entry) { Animals.$table.removeChild(document.getElementById("entry-"+ entry.id)); } }; Animals.init();

    Read the article

  • Mobile Safari 5mb HTML5 application cache limit?

    - by JFH
    It's becoming evident in my testing that there's a 5mb size limit on Mobile Safari's implementation of HTML5's application cache. Does anyone know how to circumvent or raise this? Is there some unexposed meta tag that I should know about? I have to cache some video content for an offline app and 5mb is not going to be enough.

    Read the article

  • How to store values in database C# ?

    - by hello-all
    Hello all, I have a form that has text boxes, buttons on it for the user to sign up and sign in. I need to store the entered sign up credentials in any database(Oracle, Service based database, local database). Then when he tries to sign in, entered credentials should be compared with stored sign up values for authentication. This is done in visual studio, c#. Can anyone please give me hints or any references? Thank you

    Read the article

  • DOM Storage and locks

    - by user535759
    Since DOM storage and its equivalencies persist in between tabs and windows, I've thought about using it for message passing. The problem is that fetch and store are different operations, and therefore not atomic. I have models that rely on UUID generation, conflict resolutions, and beaconing to do the small subset of what I need to do, but my real question is this: Since the local storage is a shared memory resource, what are the locking mechanisms available for mutual access?

    Read the article

  • How do I send data from Java to Flash locally?

    - by terence
    I have a website with a Java applet and a Flash application. I want the Java applet to send data to the Flash application locally. What's the best way to do this? The data I want to send are potentially large images (possibly up to 1MB in size). This means sending a base64 string to javascript and then to Flash would probably be too cumbersome. I don't want to have to contact external servers or anything; all of it should be possible locally and offline. Is there some easy way to just send this sort of data around? If I saved the file locally first, Flash wouldn't be able to access that, would it?

    Read the article

  • choosing an image locally from http url and serving that image without a server round trip

    - by serverman
    Hi folks I am a complete novice to Flash (never created anything in flash). I am quite familiar with web applications (J2EE based) and have a reasonable expertise in Javascript. Here is my requirement. I want the user to select (via an html form) an image. Normally in the post, this image would be sent to server and may be stored there to be served later. I do not want that. I want to store this image locally and then serve it via HTTP to the user. So, the flow is: 1. Go to the "select image url":mywebsite.com/selectImage Browse the image and select the image This would transfer control locally to some code running on the client (Javascript or flash), which would then store the image locally at some place on the client machine. Go to the "show image url": mywebsite.com/showImage This would eventually result in some client code running on the browser that retrieves the image and renders it (without any server round trips.) I considered the following options: Use HTML5 local storage. Since I am a complete novice to flash, I looked into this. I found that it is fairly straightforward to store and retrieve images in javascript (only strings are allowed but I am hoping storing base64 encoded strings would work at least for small images). However, how do I serve the image via http url that points to my server without a server round trip? I saw the interesting article at http://hacks.mozilla.org/category/fileapi/ but that would work only in firefox and I need to work on all latest browsers (at least the ones supporting HTML5 local storage) Use flash SharedObjects. OK, this would have been good - the only thing is I am not sure where to start. Snippets of actionscripts to do this are scattered everywhere but I do not know how to use those scripts in an actual html page:) I do not need to create any movies or anything - just need to store an image and serve it locally. If I go this route, I would also use it to store other "strings" locally. If you suggest this, please give me the exact steps (could be pointers to other web sites) on how to do this. I would like to avoid paying for any flash development environment software ideally:) Thank you!

    Read the article

  • Greasemonkey failing to GM_setValue()

    - by HonoredMule
    I have a Greasemonkey script that uses a Javascript object to maintain some stored objects. It covers quite a large volume of information, but substantially less than it successfully stored and retrieved prior to encountering my problem. One value refuses to save, and I can not for the life of me determine why. The following problem code: Works for other larger objects being maintained. Is presently handling a smaller total amount of data than previously worked. Is not colliding with any function or other object definitions. Can (optionally) successfully save the problem storage key as "{}" during code startup. this.save = function(table) { var tables = this.tables; if(table) tables = [table]; for(i in tables) { logger.log(this[tables[i]]); logger.log(JSON.stringify(this[tables[i]])); GM_setValue(tables[i] + "_" + this.user, JSON.stringify(this[tables[i]])); logger.log(tables[i] + "_" + this.user + " updated"); logger.log(GM_getValue(tables[i] + "_" + this.user)); } } The problem is consistently reproducible and the logging statments produce the following output in Firebug: Object { 54,10 = Object } // Expansion shows complete contents as expected, but there is one oddity--Firebug highlights the array keys in purple instead of the usual black for anonymous objects. {"54,10":{"x":54,"y":10,"name":"Lucky Pheasant"}} // The correctly parsed string. bookmarks_HonoredMule saved undefined I have tried altering the format of the object keys, to no effect. Further narrowing down the issue is that this particular value is successfully saved as an empty object ("{}") during code initialization, but skipping that also does not help. Reloading the page confirms that saving of the nonempty object truly failed. Any idea what could cause this behavior? I've thoroughly explored the possibility of hitting size constraints, but it doesn't appear that can be the problem--as previously mentioned, I've already reduced storage usage. Other larger objects save still, and the total number of objects, which was not high already, has further been reduced by an amount greater than the quantity of data I'm attempting to store here.

    Read the article

  • Which would be better? Storing/access data in a local text file, or in a database?

    - by TerranRich
    Basically, I'm still working on a puzzle-related website (micro-site really), and I'm making a tool that lets you input a word pattern (e.g. "r??n") and get all the matching words (in this case: rain, rein, ruin, etc.). Should I store the words in local text files (such as words5.txt, which would have a return-delimited list of 5-letter words), or in a database (such as the table Words5, which would again store 5-letter words)? I'm looking at the problem in terms of data retrieval speeds and CPU server load. I could definitely try it both ways and record the times taken for several runs with both methods, but I'd rather hear it from people who might have had experience with this. Which method is generally better overall?

    Read the article

  • Local development using HTML5 storage

    - by jasongonzales
    I am experimenting with HTML5 local storage functionality, but was frustrated to learn that the browser won't allow local storage when the file is local. My guess is that the browser (Chrome in my case, FF too) wants to see a domain rather than a file location. Has anyone here discovered a workaround for developing locally? Perhaps setting up a local domain? That sounds like too much trouble. There should just be a developer option in the browser, grrrrrr.

    Read the article

  • Bash mine script, please

    - by HomelyPoet
    The script, in and of its self, is fairly self-explanatory. Use if You so desire; any and all criticism wouldst be appreciated, as wouldst any suggestions for improvement. First iteration was writ upon OS X 10.5.8 Leopard, current iteration was run upon OS X 10.6.4 Snow Leopard with Safari 5.0.2 (6533.18.5). Also, any illumination as to why the first line ' if [ -f ] ' works, but ' if [ -f ~/Library/Safari/LocalStorage/*.localstorage ] ' generates an error? [yes, I am a bit of a Noob] Code: #! /bin/bash # SafariClear0.0.6 if [ -f ] then cat /dev/null > ~/Library/Safari/LocalStorage/*.localstorage rm -f ~/Library/Safari/LocalStorage/*.localstorage fi if [ -f ~/Library/Safari/LocalStorage/*.localstorage ] then echo "Oy vey!" fi cd ~/Library/Safari/ cat /dev/null > WebpageIcons.db cat /dev/null > TopSites.plist cat /dev/null > LocationPermissions.plist cat /dev/null > LastSession.plist cat /dev/null > History.plist echo "Clear" exit

    Read the article

  • How to push oath token to LocalStorage or LocalSession and listen to the Storage Event? (SoundCloud Php/JS bug workaround)

    - by afxjzs
    This references this issue: Javascript SDK connect() function not working in chrome I asked for more information on how to resolve with localstorage and was asked to create a new topic. The answer was "A workaround is instead of using window.opener, push the oauth token into LocalStorage or SessionStorage and have the opener window listen to the Storage event." but i have no idea how to do that. It seems really simple, but i don't know where to start. I couldn't find an relevant examples. thanks for your help!

    Read the article

  • Using HTML 5 SessionState to save rendered Page Content

    - by Rick Strahl
    HTML 5 SessionState and LocalStorage are very useful and super easy to use to manage client side state. For building rich client side or SPA style applications it's a vital feature to be able to cache user data as well as HTML content in order to swap pages in and out of the browser's DOM. What might not be so obvious is that you can also use the sessionState and localStorage objects even in classic server rendered HTML applications to provide caching features between pages. These APIs have been around for a long time and are supported by most relatively modern browsers and even all the way back to IE8, so you can use them safely in your Web applications. SessionState and LocalStorage are easy The APIs that make up sessionState and localStorage are very simple. Both object feature the same API interface which  is a simple, string based key value store that has getItem, setItem, removeitem, clear and  key methods. The objects are also pseudo array objects and so can be iterated like an array with  a length property and you have array indexers to set and get values with. Basic usage  for storing and retrieval looks like this (using sessionStorage, but the syntax is the same for localStorage - just switch the objects):// set var lastAccess = new Date().getTime(); if (sessionStorage) sessionStorage.setItem("myapp_time", lastAccess.toString()); // retrieve in another page or on a refresh var time = null; if (sessionStorage) time = sessionStorage.getItem("myapp_time"); if (time) time = new Date(time * 1); else time = new Date(); sessionState stores data that is browser session specific and that has a liftetime of the active browser session or window. Shut down the browser or tab and the storage goes away. localStorage uses the same API interface, but the lifetime of the data is permanently stored in the browsers storage area until deleted via code or by clearing out browser cookies (not the cache). Both sessionStorage and localStorage space is limited. The spec is ambiguous about this - supposedly sessionStorage should allow for unlimited size, but it appears that most WebKit browsers support only 2.5mb for either object. This means you have to be careful what you store especially since other applications might be running on the same domain and also use the storage mechanisms. That said 2.5mb worth of character data is quite a bit and would go a long way. The easiest way to get a feel for how sessionState and localStorage work is to look at a simple example. You can go check out the following example online in Plunker: http://plnkr.co/edit/0ICotzkoPjHaWa70GlRZ?p=preview which looks like this: Plunker is an online HTML/JavaScript editor that lets you write and run Javascript code and similar to JsFiddle, but a bit cleaner to work in IMHO (thanks to John Papa for turning me on to it). The sample has two text boxes with counts that update session/local storage every time you click the related button. The counts are 'cached' in Session and Local storage. The point of these examples is that both counters survive full page reloads, and the LocalStorage counter survives a complete browser shutdown and restart. Go ahead and try it out by clicking the Reload button after updating both counters and then shutting down the browser completely and going back to the same URL (with the same browser). What you should see is that reloads leave both counters intact at the counted values, while a browser restart will leave only the local storage counter intact. The code to deal with the SessionStorage (and LocalStorage not shown here) in the example is isolated into a couple of wrapper methods to simplify the code: function getSessionCount() { var count = 0; if (sessionStorage) { var count = sessionStorage.getItem("ss_count"); count = !count ? 0 : count * 1; } $("#txtSession").val(count); return count; } function setSessionCount(count) { if (sessionStorage) sessionStorage.setItem("ss_count", count.toString()); } These two functions essentially load and store a session counter value. The two key methods used here are: sessionStorage.getItem(key); sessionStorage.setItem(key,stringVal); Note that the value given to setItem and return by getItem has to be a string. If you pass another type you get an error. Don't let that limit you though - you can easily enough store JSON data in a variable so it's quite possible to pass complex objects and store them into a single sessionStorage value:var user = { name: "Rick", id="ricks", level=8 } sessionStorage.setItem("app_user",JSON.stringify(user)); to retrieve it:var user = sessionStorage.getItem("app_user"); if (user) user = JSON.parse(user); Simple! If you're using the Chrome Developer Tools (F12) you can also check out the session and local storage state on the Resource tab:   You can also use this tool to refresh or remove entries from storage. What we just looked at is a purely client side implementation where a couple of counters are stored. For rich client centric AJAX applications sessionStorage and localStorage provide a very nice and simple API to store application state while the application is running. But you can also use these storage mechanisms to manage server centric HTML applications when you combine server rendering with some JavaScript to perform client side data caching. You can both store some state information and data on the client (ie. store a JSON object and carry it forth between server rendered HTML requests) or you can use it for good old HTTP based caching where some rendered HTML is saved and then restored later. Let's look at the latter with a real life example. Why do I need Client-side Page Caching for Server Rendered HTML? I don't know about you, but in a lot of my existing server driven applications I have lists that display a fair amount of data. Typically these lists contain links to then drill down into more specific data either for viewing or editing. You can then click on a link and go off to a detail page that provides more concise content. So far so good. But now you're done with the detail page and need to get back to the list, so you click on a 'bread crumbs trail' or an application level 'back to list' button and… …you end up back at the top of the list - the scroll position, the current selection in some cases even filters conditions - all gone with the wind. You've left behind the state of the list and are starting from scratch in your browsing of the list from the top. Not cool! Sound familiar? This a pretty common scenario with server rendered HTML content where it's so common to display lists to drill into, only to lose state in the process of returning back to the original list. Look at just about any traditional forums application, or even StackOverFlow to see what I mean here. Scroll down a bit to look at a post or entry, drill in then use the bread crumbs or tab to go back… In some cases returning to the top of a list is not a big deal. On StackOverFlow that sort of works because content is turning around so quickly you probably want to actually look at the top posts. Not always though - if you're browsing through a list of search topics you're interested in and drill in there's no way back to that position. Essentially anytime you're actively browsing the items in the list, that's when state becomes important and if it's not handled the user experience can be really disrupting. Content Caching If you're building client centric SPA style applications this is a fairly easy to solve problem - you tend to render the list once and then update the page content to overlay the detail content, only hiding the list temporarily until it's used again later. It's relatively easy to accomplish this simply by hiding content on the page and later making it visible again. But if you use server rendered content, hanging on to all the detail like filters, selections and scroll position is not quite as easy. Or is it??? This is where sessionStorage comes in handy. What if we just save the rendered content of a previous page, and then restore it when we return to this page based on a special flag that tells us to use the cached version? Let's see how we can do this. A real World Use Case Recently my local ISP asked me to help out with updating an ancient classifieds application. They had a very busy, local classifieds app that was originally an ASP classic application. The old app was - wait for it: frames based - and even though I lobbied against it, the decision was made to keep the frames based layout to allow rapid browsing of the hundreds of posts that are made on a daily basis. The primary reason they wanted this was precisely for the ability to quickly browse content item by item. While I personally hate working with Frames, I have to admit that the UI actually works well with the frames layout as long as you're running on a large desktop screen. You can check out the frames based desktop site here: http://classifieds.gorge.net/ However when I rebuilt the app I also added a secondary view that doesn't use frames. The main reason for this of course was for mobile displays which work horribly with frames. So there's a somewhat mobile friendly interface to the interface, which ditches the frames and uses some responsive design tweaking for mobile capable operation: http://classifeds.gorge.net/mobile  (or browse the base url with your browser width under 800px)   Here's what the mobile, non-frames view looks like:   As you can see this means that the list of classifieds posts now is a list and there's a separate page for drilling down into the item. And of course… originally we ran into that usability issue I mentioned earlier where the browse, view detail, go back to the list cycle resulted in lost list state. Originally in mobile mode you scrolled through the list, found an item to look at and drilled in to display the item detail. Then you clicked back to the list and BAM - you've lost your place. Because there are so many items added on a daily basis the full list is never fully loaded, but rather there's a "Load Additional Listings"  entry at the button. Not only did we originally lose our place when coming back to the list, but any 'additionally loaded' items are no longer there because the list was now rendering  as if it was the first page hit. The additional listings, and any filters, the selection of an item all were lost. Major Suckage! Using Client SessionStorage to cache Server Rendered Content To work around this problem I decided to cache the rendered page content from the list in SessionStorage. Anytime the list renders or is updated with Load Additional Listings, the page HTML is cached and stored in Session Storage. Any back links from the detail page or the login or write entry forms then point back to the list page with a back=true query string parameter. If the server side sees this parameter it doesn't render the part of the page that is cached. Instead the client side code retrieves the data from the sessionState cache and simply inserts it into the page. It sounds pretty simple, and the overall the process is really easy, but there are a few gotchas that I'll discuss in a minute. But first let's look at the implementation. Let's start with the server side here because that'll give a quick idea of the doc structure. As I mentioned the server renders data from an ASP.NET MVC view. On the list page when returning to the list page from the display page (or a host of other pages) looks like this: https://classifieds.gorge.net/list?back=True The query string value is a flag, that indicates whether the server should render the HTML. Here's what the top level MVC Razor view for the list page looks like:@model MessageListViewModel @{ ViewBag.Title = "Classified Listing"; bool isBack = !string.IsNullOrEmpty(Request.QueryString["back"]); } <form method="post" action="@Url.Action("list")"> <div id="SizingContainer"> @if (!isBack) { @Html.Partial("List_CommandBar_Partial", Model) <div id="PostItemContainer" class="scrollbox" xstyle="-webkit-overflow-scrolling: touch;"> @Html.Partial("List_Items_Partial", Model) @if (Model.RequireLoadEntry) { <div class="postitem loadpostitems" style="padding: 15px;"> <div id="LoadProgress" class="smallprogressright"></div> <div class="control-progress"> Load additional listings... </div> </div> } </div> } </div> </form> As you can see the query string triggers a conditional block that if set is simply not rendered. The content inside of #SizingContainer basically holds  the entire page's HTML sans the headers and scripts, but including the filter options and menu at the top. In this case this makes good sense - in other situations the fact that the menu or filter options might be dynamically updated might make you only cache the list rather than essentially the entire page. In this particular instance all of the content works and produces the proper result as both the list along with any filter conditions in the form inputs are restored. Ok, let's move on to the client. On the client there are two page level functions that deal with saving and restoring state. Like the counter example I showed earlier, I like to wrap the logic to save and restore values from sessionState into a separate function because they are almost always used in several places.page.saveData = function(id) { if (!sessionStorage) return; var data = { id: id, scroll: $("#PostItemContainer").scrollTop(), html: $("#SizingContainer").html() }; sessionStorage.setItem("list_html",JSON.stringify(data)); }; page.restoreData = function() { if (!sessionStorage) return; var data = sessionStorage.getItem("list_html"); if (!data) return null; return JSON.parse(data); }; The data that is saved is an object which contains an ID which is the selected element when the user clicks and a scroll position. These two values are used to reset the scroll position when the data is used from the cache. Finally the html from the #SizingContainer element is stored, which makes for the bulk of the document's HTML. In this application the HTML captured could be a substantial bit of data. If you recall, I mentioned that the server side code renders a small chunk of data initially and then gets more data if the user reads through the first 50 or so items. The rest of the items retrieved can be rather sizable. Other than the JSON deserialization that's Ok. Since I'm using SessionStorage the storage space has no immediate limits. Next is the core logic to handle saving and restoring the page state. At first though this would seem pretty simple, and in some cases it might be, but as the following code demonstrates there are a few gotchas to watch out for. Here's the relevant code I use to save and restore:$( function() { … var isBack = getUrlEncodedKey("back", location.href); if (isBack) { // remove the back key from URL setUrlEncodedKey("back", "", location.href); var data = page.restoreData(); // restore from sessionState if (!data) { // no data - force redisplay of the server side default list window.location = "list"; return; } $("#SizingContainer").html(data.html); var el = $(".postitem[data-id=" + data.id + "]"); $(".postitem").removeClass("highlight"); el.addClass("highlight"); $("#PostItemContainer").scrollTop(data.scroll); setTimeout(function() { el.removeClass("highlight"); }, 2500); } else if (window.noFrames) page.saveData(null); // save when page loads $("#SizingContainer").on("click", ".postitem", function() { var id = $(this).attr("data-id"); if (!id) return true; if (window.noFrames) page.saveData(id); var contentFrame = window.parent.frames["Content"]; if (contentFrame) contentFrame.location.href = "show/" + id; else window.location.href = "show/" + id; return false; }); … The code starts out by checking for the back query string flag which triggers restoring from the client cache. If cached the cached data structure is read from sessionStorage. It's important here to check if data was returned. If the user had back=true on the querystring but there is no cached data, he likely bookmarked this page or otherwise shut down the browser and came back to this URL. In that case the server didn't render any detail and we have no cached data, so all we can do is redirect to the original default list view using window.location. If we continued the page would render no data - so make sure to always check the cache retrieval result. Always! If there is data the it's loaded and the data.html data is restored back into the document by simply injecting the HTML back into the document's #SizingContainer element:$("#SizingContainer").html(data.html); It's that simple and it's quite quick even with a fully loaded list of additional items and on a phone. The actual HTML data is stored to the cache on every page load initially and then again when the user clicks on an element to navigate to a particular listing. The former ensures that the client cache always has something in it, and the latter updates with additional information for the selected element. For the click handling I use a data-id attribute on the list item (.postitem) in the list and retrieve the id from that. That id is then used to navigate to the actual entry as well as storing that Id value in the saved cached data. The id is used to reset the selection by searching for the data-id value in the restored elements. The overall process of this save/restore process is pretty straight forward and it doesn't require a bunch of code, yet it yields a huge improvement in the usability of the site on mobile devices (or anybody who uses the non-frames view). Some things to watch out for As easy as it conceptually seems to simply store and retrieve cached content, you have to be quite aware what type of content you are caching. The code above is all that's specific to cache/restore cycle and it works, but it took a few tweaks to the rest of the script code and server code to make it all work. There were a few gotchas that weren't immediately obvious. Here are a few things to pay attention to: Event Handling Logic Timing of manipulating DOM events Inline Script Code Bookmarking to the Cache Url when no cache exists Do you have inline script code in your HTML? That script code isn't going to run if you restore from cache and simply assign or it may not run at the time you think it would normally in the DOM rendering cycle. JavaScript Event Hookups The biggest issue I ran into with this approach almost immediately is that originally I had various static event handlers hooked up to various UI elements that are now cached. If you have an event handler like:$("#btnSearch").click( function() {…}); that works fine when the page loads with server rendered HTML, but that code breaks when you now load the HTML from cache. Why? Because the elements you're trying to hook those events to may not actually be there - yet. Luckily there's an easy workaround for this by using deferred events. With jQuery you can use the .on() event handler instead:$("#SelectionContainer").on("click","#btnSearch", function() {…}); which monitors a parent element for the events and checks for the inner selector elements to handle events on. This effectively defers to runtime event binding, so as more items are added to the document bindings still work. For any cached content use deferred events. Timing of manipulating DOM Elements Along the same lines make sure that your DOM manipulation code follows the code that loads the cached content into the page so that you don't manipulate DOM elements that don't exist just yet. Ideally you'll want to check for the condition to restore cached content towards the top of your script code, but that can be tricky if you have components or other logic that might not all run in a straight line. Inline Script Code Here's another small problem I ran into: I use a DateTime Picker widget I built a while back that relies on the jQuery date time picker. I also created a helper function that allows keyboard date navigation into it that uses JavaScript logic. Because MVC's limited 'object model' the only way to embed widget content into the page is through inline script. This code broken when I inserted the cached HTML into the page because the script code was not available when the component actually got injected into the page. As the last bullet - it's a matter of timing. There's no good work around for this - in my case I pulled out the jQuery date picker and relied on native <input type="date" /> logic instead - a better choice these days anyway, especially since this view is meant to be primarily to serve mobile devices which actually support date input through the browser (unlike desktop browsers of which only WebKit seems to support it). Bookmarking Cached Urls When you cache HTML content you have to make a decision whether you cache on the client and also not render that same content on the server. In the Classifieds app I didn't render server side content so if the user comes to the page with back=True and there is no cached content I have to a have a Plan B. Typically this happens when somebody ends up bookmarking the back URL. The easiest and safest solution for this scenario is to ALWAYS check the cache result to make sure it exists and if not have a safe URL to go back to - in this case to the plain uncached list URL which amounts to effectively redirecting. This seems really obvious in hindsight, but it's easy to overlook and not see a problem until much later, when it's not obvious at all why the page is not rendering anything. Don't use <body> to replace Content Since we're practically replacing all the HTML in the page it may seem tempting to simply replace the HTML content of the <body> tag. Don't. The body tag usually contains key things that should stay in the page and be there when it loads. Specifically script tags and elements and possibly other embedded content. It's best to create a top level DOM element specifically as a placeholder container for your cached content and wrap just around the actual content you want to replace. In the app above the #SizingContainer is that container. Other Approaches The approach I've used for this application is kind of specific to the existing server rendered application we're running and so it's just one approach you can take with caching. However for server rendered content caching this is a pattern I've used in a few apps to retrofit some client caching into list displays. In this application I took the path of least resistance to the existing server rendering logic. Here are a few other ways that come to mind: Using Partial HTML Rendering via AJAXInstead of rendering the page initially on the server, the page would load empty and the client would render the UI by retrieving the respective HTML and embedding it into the page from a Partial View. This effectively makes the initial rendering and the cached rendering logic identical and removes the server having to decide whether this request needs to be rendered or not (ie. not checking for a back=true switch). All the logic related to caching is made on the client in this case. Using JSON Data and Client RenderingThe hardcore client option is to do the whole UI SPA style and pull data from the server and then use client rendering or databinding to pull the data down and render using templates or client side databinding with knockout/angular et al. As with the Partial Rendering approach the advantage is that there's no difference in the logic between pulling the data from cache or rendering from scratch other than the initial check for the cache request. Of course if the app is a  full on SPA app, then caching may not be required even - the list could just stay in memory and be hidden and reactivated. I'm sure there are a number of other ways this can be handled as well especially using  AJAX. AJAX rendering might simplify the logic, but it also complicates search engine optimization since there's no content loaded initially. So there are always tradeoffs and it's important to look at all angles before deciding on any sort of caching solution in general. State of the Session SessionState and LocalStorage are easy to use in client code and can be integrated even with server centric applications to provide nice caching features of content and data. In this post I've shown a very specific scenario of storing HTML content for the purpose of remembering list view data and state and making the browsing experience for lists a bit more friendly, especially if there's dynamically loaded content involved. If you haven't played with sessionStorage or localStorage I encourage you to give it a try. There's a lot of cool stuff that you can do with this beyond the specific scenario I've covered here… Resources Overview of localStorage (also applies to sessionStorage) Web Storage Compatibility Modernizr Test Suite© Rick Strahl, West Wind Technologies, 2005-2013Posted in JavaScript  HTML5  ASP.NET  MVC   Tweet !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs"); (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })();

    Read the article

  • How do I use HTML5's localStorage in a Google Chrome extension?

    - by davidkennedy85
    I am trying to develop an extension that will work with Awesome New Tab Page. I've followed the author's advice to the letter, but it doesn't seem like any of the script I add to my background page is being executed at all. Here's my background page: <script> var info = { poke: 1, width: 1, height: 1, path: "widget.html" } chrome.extension.onRequestExternal.addListener(function(request, sender, sendResponse) { if (request === "mgmiemnjjchgkmgbeljfocdjjnpjnmcg-poke") { chrome.extension.sendRequest( sender.id, { head: "mgmiemnjjchgkmgbeljfocdjjnpjnmcg-pokeback", body: info, } ); } }); function initSelectedTab() { localStorage.setItem("selectedTab", "Something"); } initSelectedTab(); </script> Here is manifest.json: { "update_url": "http://clients2.google.com/service/update2/crx", "background_page": "background.html", "name": "Test Widget", "description": "Test widget for mgmiemnjjchgkmgbeljfocdjjnpjnmcg.", "icons": { "128": "icon.png" }, "version": "0.0.1" } Here is the relevant part of widget.html: <script> var selectedTab = localStorage.getItem("selectedTab"); document.write(selectedTab); </script> Every time, the browser just displays null. The local storage isn't being set at all, which makes me think the background page is completely disconnected. Do I have something wired up incorrectly?

    Read the article

  • Online video tutorials for HTML 5

    - by Albers
    Here are some of the best introductory HTML5 videos I have found online/for free. Mix 2011: HTML5 for Skeptics - Scott Stansfield channel9.msdn.com/Events/MIX/MIX11/EXT21 Filling the HTML5 Gaps with Polyfills and Shims - Ray Bango channel9.msdn.com/Events/MIX/MIX11/HTM04 50 Performance Tricks to Make Your HTML5 Web Sites Faster - Jason Weber channel9.msdn.com/Events/MIX/MIX11/HTM01 TechEd 2011 HTML5 and CSS3 Techniques You Can Use Today - Todd Anglin channel9.msdn.com/Events/TechEd/NorthAmerica/2011/DEV334 Google IO HTML5 Showcase for Web Developers: The Wow and the How www.youtube.com/watch?v=WlwY6_W4VG8 css-tricks localStorage for Forms - Chris Coyier css-tricks.com/video-screencasts/96-localstorage-for-forms/ Best Practices with Dynamic Content - Chris Coyier This one talks about Hash Tags - take a look at the History API too css-tricks.com/video-screencasts/85-best-practices-dynamic-content/ localStorage for Forms - Chris Coyier css-tricks.com/video-screencasts/96-localstorage-for-forms/ Overview of HTML5 Forms Types, Attributes, and Elements - Chris Coyier css-tricks.com/video-screencasts/99-overview-of-html5-forms-types-attributes-and-elements/ Bruce Lawson - HTML5: Who, What, When, Why www.ubelly.com/2011/10/bruce-lawson-html5-who-what-when-why/ Bruce Lawson is an evangelist for Opera, and in this video he provides an overview including the history & philosophy of HTML5.

    Read the article

  • How to read & write contents of a div from localstorage in chrome extensions?

    - by Minas Abovyan
    I am trying to build an extension that will allow users to put some parameters into a text box in the popup, generate a link using that information and add it to the said popup. I have all that working, but needless to say, it gets flushed every time the user opens the extension anew. I'd like the info that has been put in there to stay, but can't seem to get it to work. Here's what I have thus far: manifest.json { "manifest_version": 2, "name": "Test", "description": "Test Extension", "version": "1.0", "permissions": [ "http://*/*", "https://*/*" ], "browser_action": { "default_title": "This is a test", "default_popup": "popup.html" } } popup.html <!DOCTYPE html> <html> <head> </head> <body> <div id="linkContainer"/> <input type="text" id="catsList"/> <button type="button" id="addToList">Add</button> <script src="popup.js"></script> </body> </html> popup.js function addCats() { var a = document.createElement('a'); a.appendChild(document.createTextNode(document.getElementById('catsList').value)); a.setAttribute('href', 'http://google.com'); var p = document.createElement('p'); p.appendChild(a) document.getElementById('linkContainer').appendChild(p); indexLinks() } function indexLinks() { var links = document.getElementsByTagName("a"); for (var i = 0; i < links.length; i++) { (function () { var ln = links[i]; var location = ln.href; ln.onclick = function () { chrome.tabs.create({active: true, url: location}); }; })(); } }; document.getElementById('addToList').onclick = addCats; My guess is that I need something along the lines of localStorage['cointainer'] = document.getElementById('linkContainer'); at the end of addCats() and a call to something like function loadLocalStorage() { var container = document.getElementById('linkContainer'); container.innerHTML = localStorage['container']; } at the beginning, but doing that didn't work. Not sure what's going wrong. Also,if there is a different way to save users' additions, I'd be open to them.

    Read the article

  • Using html5 localstorage to retrieve data from server, to allow editing of and appending to data sou

    - by Adam
    So, I'm creating a standard user-data collection form that will be used by standard web browsers, as well as the iPhone and iPad. The app will allow users to create new records, as well as edit and delete existing records. I've gotten the gist of using html5's 'localstorage' to create a client-side data source and am looking for direction for getting existing data from a server into a client-side data source, and then being able to edit or delete that data, or to append a new record to the existing data. Finally, being able to save the updated data back to the server. It sounds like a lot, I know. But I've been pouring through html5 tuts and can't seem to find exactly what I'm looking for.

    Read the article

  • Is anyone else receiving a QUOTA_EXCEEDED_ERR on their iPad when accessing localStorage?

    - by Kevin
    I have a web application written in JavaScript that runs successfully on the desktop via Safari as well as on the iPhone. We are looking at porting this application to the iPad and we are running into a problem where we are seeing QUOTA_EXCEEDED_ERR when storing a relatively small amount of data within the localStorage on the device. I know what this error means, but I just don't think I'm storing all that much data. Is anyone else doing something similar? And seeing/not seeing this problem? Kevin...

    Read the article

< Previous Page | 1 2 3 4 5  | Next Page >