Why does localStorage.getItem fail only in IE9? - javascript

This works perfectly in Chrome and Firefox:
var webStorageSupported = ('localStorage' in window) && window['localStorage'] !== null;
if (webStorageSupported && localStorage.getItem("get_list_center") !== null) {
document.getElementById('mail_listing').innerHTML = localStorage.getItem("get_list_center");
}
But I get an unknown exception when I view the page in IE9. I am able to get both the element and the content in the local storage if I type: document.getElementById('mail_listing').innerHTML;
and localStorage.getItem("get_list_center"); separately in console.
When I try to assign the innerHTML as the local storage, unknown exception occurs. What Gives???
Edit: As per suggestion from comment, I've tried to get the local storage in a separate variable then assign that variable inside the innerhtml. It turned out that localstorage was indeed retrieving the HTML formatted code, but it wasn't able to save the whole string:
<table width="100%">......
<TD width=\"7%\" align=right>12K </TD></TR></TBODY></TABLE></DIV>\r\n<DIV style=\"DISPLAY: no
[[CUT OFF FROM HERE]]
I was under the impression that localstorage saves upto 5 MB of text, which is the case for Chrome and Firefox, but maybe this isn't the case for IE9 (Edit: After googling, IE9 supports up to 10MB so clearly it's something else). What can I do to solve this problem?
Edit2: I've verified that localStorage is correctly assigning the entire HTML content if it is retrieved right after the content has been set:
localStorage.setItem('get_list_center', document.body.innerHTML);
var x = localStorage.getItem('get_list_center'); //GETS THE WHOLE HTML CONTENT CORRECTLY.
It's just that when I'm getting the content from somewhere else where I need it from, the content gets cut off. localstorage isn't tampered anywhere else.

If you are browsing from a file: URL, this is just one of many reasons we should all switch to Firefox -- IE9 hates localStorage on local documents.

Related

IndexedDB result sometimes corrupt

I'm using "localforage" in a project and have a mysterious problem.
Through redux / immutableJS I'm storing some settings like "locale", reading it from storage sometimes works but often not.
I hooked into localeforages query system:
var store = transaction.objectStore(self._dbInfo.storeName);
var req = store.get(key);
req.onsuccess = function() {
var value = req.result;
console.log(value);
// ...
}
This should output the plain, serialized immutable data string:
"[\"~#iM\",[\"locale\",\"de_DE\"]]"
But very often I instead receive this:
"[\"~#iM\",[\"locale\",null]]"
When the error occurs the Developer Tools' "application" tab is showing the correct value (so not NULL).
Same codebase, absolutely NO CHANGES, shows different behavior in current Chrome (never working) and Firefox (sometimes working).
Anyone got a similar error in the past?
I don't understand how a plain string value could sometimes work and sometimes not.

Get "null" in IE10 localStorage if item is undefined [duplicate]

I'm using localStorage in my JS application and I was wondering why IE9 claims localStorage == undefined. As far as I know, IE8 supports it, is here any way to get it working in the new version?
Are you testing this on a local HTML file? i.e. a file:/// URL?
localStorage is only available on HTTP websites. That hasn't changed in IE9 Dev Preview.
IE 11 WORKS
All you need two do add file://127.0.0.1 to the trusted zones under the security
tab (NOTE: make sure https check box IS not checked)
add this line to the top or your script, depending on your code you may not need to unless you get could not connect to the internet.
!localStorage && (l = location, p = l.pathname.replace(/(^..)(:)/, "$1$$"), (l.href = l.protocol + "//127.0.0.1" + p));
if (typeof(Storage) != "undefined") {
// Store
localStorage.setItem("lastname", "Smith");
// Retrieve
alert(localStorage.getItem("lastname"));
} else {
alert("Sorry, your browser does not support Web Storage...");
}
Try to open the file like this
file://127.0.0.1/c$/pathtofile/file.html

I cant read my cookie out in google chrome but I can in all other browsers

I am setting a cookie to hide a cookie notice on a my website.
This works fine in all other browsers but Google Chrome(and Opera to it seems) (not even tested in IE yet)
Here is my code that reads out the cookies and makes the decision whether to run the show function or do nothing.
This function is called up on page load
checkCookie = function() {
var myCookieSet = getCookie("useofcookies");
if (myCookieSet != "closed"){
alert('cookie is not set and = '+ myCookieSet);
// run the show info bar function
init();
}else {
alert('cookie HAS BEEN set and = '+ myCookieSet);
}
};
I cannot figure out what I have done wrong.
Full js file can be found here:
Cookie Notice - Pastebin
Any clues as to why would this is happening in Chrome alone would be a great help
Have you tried clearing your cache and cookies? IE a 'clean browser'?
The code looks fine and when I use your code it seems to work for me. Even in IE 8/9

What other options for replacing entire HTML document via W3C DOM?

I am curious about people's experiences with replacing the entire document at runtime in an Ajax web app. It's rare, but I've found a few situations where the app requires an entire page rebuild and everything is present locally without needing another server round-trip.
I can easily prepare the new document as either a new DOM tree or as a String. So I'm evaluating the trade-offs for various approaches.
If I want to use the String approach this seems to work:
document.open();
document.write(newStringDoc);
document.close();
Most browsers do this just fine, but many have a slight flicker when re-rendering. I've noticed that on the 2nd time through Firefox 4.0b7 will just sit there and spin as if it is loading. Hitting the stop button on the location bar seems to complete the page render. (Edit: this appears to be fixed in 4.0b8) Also this method seems to prevent the user from hitting refresh to reload the current URL (it reloads the dynamically generated page).
If I use a new DOM tree approach (which has different advantages/disadvantages in flexibility and speed), then this seems to work:
document.replaceChild(newDomDoc, document.documentElement);
Most browsers seem to handle this perfectly fine without flicker. Unfortunately, IE9 beta throws "DOM Exception: HIERARCHY_REQUEST_ERR (3)" on replaceChild and never completes. I haven't tried the latest preview release to see if this is just a new bug that got fixed. (Edit: this appears to be fixed in RC1.)
My question: does anyone have a different approach than either of these? Does anyone have any other caveats where perhaps a particular browser fundamentally breaks down with one of these approaches?
Update: Perhaps this will add context and help the imagination. Consider a situation where an application is offline. There is no server available to redirect or refresh. The necessary state of the application is already loaded (or stored) client-side. The UI is constructed from client-side templates.
I believe that Gmail uses iframes embedded within a root document. It appears the starting document for at least some of these iframes are just a bare HTML5 document which the parent document then manipulates.
Using an iframe would be another variant on the requirement to replace the current document by replacing the entire child iframe or just its document. The same situation exists though of what approach to attach the new document to the iframe.
I guess I will answer this with my own findings as I'm wrapping up my research on this.
Since the two browsers which have issues with one of these methods are both beta, I've opened bug reports which hopefully will resolve those before their full release:
Firefox 4 Beta: https://bugzilla.mozilla.org/show_bug.cgi?id=615927
Edit: Fixed in FF 4b8.
Internet Explorer 9 Beta: https://connect.microsoft.com/IE/feedback/details/626473
Edit: Fixed in IE9 RC1.
I've also found pretty consistently that this...
document.replaceChild(newDomDoc, document.documentElement);
...is 2-10x faster than this...
var doc = document.open("text/html");
doc.write(newStringDoc);
doc.close();
...even when including the time needed to build the DOM nodes vs. build the HTML string. This might be the reason for the flicker, or perhaps just another supporting argument for the DOM approach. Chrome doesn't have any flicker with either method.
Note the subtle change of storing the returned document which circumvents the bug in Firefox 4.0b7.
Also note this added MIME type which the IE docs claim is "required".
Finally, Internet Explorer seems to have a bit of trouble resolving link tags that were built before the new document is swapped in. Assigning the link href back to itself appears to patch it up.
// IE requires link repair
if (document.createStyleSheet) {
var head = document.documentElement.firstChild;
while (head && (head.tagName||"") !== "HEAD") {
head = head.nextSibling;
}
if (head) {
var link = head.firstChild;
while (link) {
if ((link.tagName||"") === "LINK") {
link.href = link.href;
}
link = link.nextSibling;
}
}
}
One could cover all bases and combine them like this...
var doc = document;
try {
var newRoot = newDoc.toDOM();
doc.replaceChild(newRoot, doc.documentElement);
// IE requires link repair
if (doc.createStyleSheet) {
var head = newRoot.firstChild;
while (head && (head.tagName||"") !== "HEAD") {
head = head.nextSibling;
}
if (head) {
var link = head.firstChild;
while (link) {
if ((link.tagName||"") === "LINK") {
link.href = link.href;
}
link = link.nextSibling;
}
}
}
} catch (ex) {
doc = doc.open("text/html");
doc.write(newDoc.toString());
doc.close();
}
...assuming you have the ability to choose your approach like I do.

IE 6/7 Access Denied trying to access a popup window.document

I'm creating a popup window with no URL source using window.open(). I don't give it a URL because soon I'll want to post a form to it. However, in the meantime I'd like to display a short "Now loading..." message so the user isn't looking at a blank page for the 2-3 seconds it'll take the form post to go through.
I tried adding Javascript that just writes to the popup window's document. That worked great in Firefox and IE 8, but failed with an Access Denied message in IE 6 and 7. Anyone know of a way around this? I would love to be able to a) hard-code some HTML into window.open(), b) learn how to update the popup's DOM in this situation, or c) hear about anything anyone can think of.
Below is the code I'm using to spawn the window:
var wref = window.open("", winName, "toolbar=1,resizable=1,menubar=1,location=1,status=1,scrollbars=1,width=800,height=600");
if (wref != null) {
try {wref.opener = self;} catch (exc) {}
// while we wait for the handoff form post to go through, display a simple wait message
$j(wref.document.body).html('Now loading …'); // EPIC FAIL
wref.focus();
IE considers "about:blank" to be a insecure URL and it won't let you talk to it. I would create a "Now Loading..." static HTML file and open that instead.
Test
<script type="text/javascript">
function test() {
window.open('javascript:opener.write(window);', '_name', 'width=200,height=200');
}
function write(w) {
w.document.write("Hello, World.");
}
</script>
Works in IE 6, 7 & 8, Opera 9.6, Firefox 2 & 3.
Does not work in Safari for Windows 3 & 4 or Google Chrome.
When it does work, it results in a pretty ugly URL in the Location box.
If the browser support listed above is acceptable, you can use the solution provided, otherwise I'd do what David said and window.open('Loading.htm' ...) where Loading.htm contains whatever content you want to display (you should probably keep it lightweight otherwise it might take longer to load and render than the form will to POST).
Also note that the winName you supply in IE must NOT have spaces... if so it will fail.
Another workaround is to open an empty "blank.htm" file on your site, then do the document.open() to access it

Categories

Resources