access web sql database between 2 html5 pages - javascript

I am new to html5 and js,if this is a very simple question, please forgive my ignorance.
But can someone please help me in figuring a solution for my case:
I have created some static html5 pages and also a offline database from my js code which is accessed across all the html5 pages.
Now i am trying to update the database from one page and want the updated database reflection across all the html5 pages.
Thanks in advance.

As you said it is offline db, store the values in some global variable before storing it in database. And in all other pages , rely on that global variable.So , if you have some data updated in page1, store it in some global variable also. And use that variable in all other pages.

To access the offline databases from several different pages, please make sure all your pages are in the same domain.
Create a fresh connection to the database on all your pages.
var db_conn = window.openDatabase( _ID_DATABASE_NAME, _ID_DATABASE_VERSION, _ID_DATABASE_DESC, _ID_DATABASE_SIZE );
All the parameters passed to the function should remain same.
In case the values you are trying to access are only a few name value pairs, try to use the concept of local storages. Following are the setter getter methods accessible across pages.
window.localStorage.setItem( 'myFirstLocalStorage_Name', 'myFirstLocalStorage_Value' );
var ls_value = window.localStorage.getItem( 'myFirstLocalStorage_Name' );
Hope you'll be able to get your values across pages.

The domain of both pages is needed to be same.
and w3c says
User agents may restrict access to the database objects to scripts
originating at the domain of the top-level document of the browsing
context, for instance denying access to the API for pages from other
domains running in iframes.

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!

Why do two web pages have different localStorage? How can I fix this?

I'm trying to pass a value from one page to another using localStorage.
Both pages use a common JS file to get/set values from localStorage.
This page sets the value appropriately using localStorage.setItem('key', 'value'): http://example.com/path/index.html
ip is parsed from the query string and written to localStorage with key db_ip.
When I try to do localStorage.getItem('db_ip') on this page, then the item is not there: http://www.example.com/path/page.html
I'm reading specs that say "every Document object whose Window object's localStorage attribute's Storage object is associated with the same storage area", so this makes me think pages can have separate localStorage by having a different Storage object.
I can see the Storage object is different between the two pages. How to I make both pages use the same Storage object?
The localStorage isin't per page, it's by domain. However like #bfavaretto mentionned, www.demandbaselabs.com and demandbaselabs.com aren't considered as the same domain.
Have a look at this answer to see how you can exchange client-side stored data between domains.

Use javascript to remember what choices the user made on previous pages?

I have some pages, on the last page I need to know what choices a user made on the two last pages.
Like this:
a.html
User has three choices here that takes him/her to different urls. I need to somehow save this choice and use it later.
Example:
<script>globalVariable1="firstchoice"</script>
b.html
This is one of three choices page and here the User have 3-4 new choices that takes him/her to different urls. I also need to save this choice somehow for later use.
Example:
<script>globalVariable2="thirdchoice"</script>
c.html
This is the page where I need to know what choices the user has made earlier. To be able to link back to those exact pages if the user wants to go back in my breadcrumb-solution.
Example:
<script>
if(globalVariable1 == "firstchoice"){
//do this
}
if(globalVariable2 == "thirdchoice"){
//do this
}
</script>
Can I do this with some global variables in javascript or how can I solve this?
Thanks
You can use localStorage. A browser API that persists key/value pairs even if you navigate between pages, reload the page or close and reopen the browser.
//setting a value
localStorage["foo"] = "bar";
//getting a value
var x = localStorage["foo"];
Using sessionStorage will also work.
//setting a value
sessionStorage["foo"] = "bar";
//getting a value
var x = sessionStorage["foo"];
Wikipedias Web Storage article describes the difference between localStorage and sessionStorage as:
Data placed in local storage is per domain (it's available to all scripts from the domain that originally stored the data) and persists after the browser is closed. Session storage is per-page-per-window and is limited to the lifetime of the window. Session storage is intended to allow separate instances of the same web application to run in different windows without interfering with each other, a use case that's not well supported by cookies.
You will have to store cookies to track the user's state. Try cookie.js. It has a really simple key-value interface that you can read about on its GitHub page.
Web pages are stateless, so you cannot share global JavaScript variables between pages.
However you can set global variables for your page and containing modules by using the value of the cookie.
Your cookies will be available on all pages of your domain for the current browser.
Example:
//Page 1: Set cookie depending on user choice
$.cookie("choice1", ValueOfChoice1);
//Page 2: Get previous user choice
globalVariable1 = $.choice1("example");
You can read Setting cookies with jQuery if you want more details about how to use cookies.
you can use localStorage or sessionStorage.
Another choice if you're using some server-side language like PHP or Asp.Net is to sore those values in the user's session on the server.

Best way to store temp data to pass from web application to desktop application using javascript

I'm looking for the best practice here.
I need to store 10 variables of information, in a certain format:
lname: [John]
fname: [Doe]
etc...
using Javascript. I was thinking about using cookies.
My scenario is as follows:
The user would be in Salesforce.com and they would enter the customer's information into a record. They would then click a button get a quote. The button, using JS, would write the Salesforce fields to a temp file (cookie maybe). From there the other MS application would pick up that file and read in the values.
How would you guys do that?
Thanks for the time.
The browser will not allow you to write files, generally speaking. For this, you'd have to use a mechanism to get out of the security sandbox, such as a signed Java applet.
Cookies are NOT a good option here. Desktop apps should not be attempting to access browser cookies; at best, it's considered "badly behaved code"; at worst, you won't be able to do it, or your app will get detected as malware. Even if it was considered OK, you'll have to write cookie-reading implementations for any browser you want to support since there is no standard for how they are locally stored.
Why not make the desktop app access the web on behalf of the user? Write SFDC quote requests to a new SFDC custom object, like Quote_Request__c or similar, and the app can query the most recent record(s) created by the user via the API.
Clipboard integration, while it sometimes seems clunky, may be a low-cost option.
If you must write to a local file of some sort, you'll need to use Flash or Java, or make the user locally save some downloaded file (like any normal browser download).
Another option would be to register your desktop app as a URL protocol handler; so, say, myquote://firstname/lastname/product/price/etc could be clicked from a web browser to launch the app and parse the "URL". May work poorly with very long/complicated data though.
Yes, cookies are certainly an option in this case. Cookies are accessible via the document global object (e.g. document.cookie). It can hold a string and an expiration date.
Here is a cookie handler I wrote:
http://jsfiddle.net/zbaJz/1/
Using this handler, you can store information in a cookie, and would be able to view as well as delete it. Then, using JSON stringify, you can pass it an object.
var name = {
'fname': 'John',
'lname': 'Doe'
};
var jsonText = JSON.stringify(name);
var cookieMonster = new Ovenmitts();
cookieMonster.bakeCookie('name', jsonText);
Then, in order to turn the data back into an object to manipulate, you would use JSON.parse.
var cookieInfo = cookieMonster.admireCookie('name');
var revived = JSON.parse(cookieInfo);
You can add a thread/task to the MS Application that watches for changes in the directory whee the cookie is created. When you detect a new file that meets your requirements you can act on it. You will need to use DirectoryInfo for this approach.
You can also create and windows or webservice that the application listen to and can pass the data this way from the web app.

Persist javascript variables between GET requests?

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

Categories