I am currently working on a some JS. It works fine in every browser apart from Microsoft Edge.
The issue is quite simple:
at the beginning of one of my scripts I declare a variable like so:
var something = localStorage.getItem('something');
Anyway the something doesn't exist yet, but the whole idea is that this can be used for reference in a later function. Firefox, Chrome, Opera and Safari don't have a problem with this but Edge does, so my question is, is the a quick fix?
Or am i going to have to rewrite my whole script because of Edge?
This is the error that edge throws by the way.
Unable to get property 'getItem' of undefined or null reference
Thanks!
Local Storage didn't work for local files in IE9, so I imagine that this is still the case in MS Edge.
I just tested it in Edge with a server on localhost and your line of code worked just fine:
> var something = localStorage.getItem('something');
> undefined
It is possible that this was a security issue in earlier versions of IE and was just never updated as the browser was developed.
Although, it appears that localStorage and sessionStorage still don't work in Edge for HTML files accessed using the 'file://' protocol.
Could you please try
var something = window.localStorage.getItem('something');
Could you also check if you have 'Enable DOM Storage' selected? You can find it under:
Internet Options -> Advanced tab -> Security group box
Also if you are running your page from local filesystem, localStorage doesn't work on IE, you have to run it from the web server.
Here is a link that provides more information of how to enable it
If someone is looking for solution older version of browser to also work to store key value for using between pages.
logic could be
function detectIE() {
var ua = window.navigator.userAgent;
var msie = ua.indexOf('MSIE ');
if (msie > 0) {
// IE 10 or older => return version number
return false;
}
var trident = ua.indexOf('Trident/');
if (trident > 0) {
// IE 11 => return version number
return false;
}
var edge = ua.indexOf('Edge/');
if (edge > 0) {
// Edge (IE 12+) => return version number
return false;
}
// other browser
return true;
}
then to set key value use something like this
if (detectIE()) { window.localStorage.setItem('key1', value1);window.localStorage.setItem('key2', value2);}else{ setCookie('key1','value1',1);var value1 = getCookie('key1');}
function setCookie(name,value,days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + (value || "") + expires + "; path=/";}
function getCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;}
also you can erase the cookie
function eraseCookie(name) {
document.cookie = name+'=; Max-Age=-99999999;'; }
Maybe DOMStorage is turned off? Test with this:
if (typeof window.Storage === 'undefined') {
alert('Storage turned off...');
}
Related
I have several domains hosted at one hosting service. All of them have a line of javascript added to the tag. It appears to be changing Math.random to something else, but I can't figure out what it's trying to accomplish.
I also can't find out where it is coming from. I have mostly WordPress domains, but 2 of my sites are static and the files there haven't been touched in years. They still show this. Also, a Drupal site has this added too.
So, I'm hoping for help with two things: 1) what is it doing? and 2) where is it coming from?
I see it in any browser I use other than the android browser on my phone. I don't see it on other sites except for 1, so I don't believe it to be related to my PC or browser.
This is the script itself. The large number in the arguments to the function call is different every time. I don't know enough about anonymous functions to really sort out what is happening here.
<script type="text/javascript">/* <![CDATA[ */Math.random=function(a,c,d,b){return function(){return 300>d++?(a=(1103515245*a+12345)%b,a/b):c()}}(237429089,Math.random,0,1<<21);(function(){function b(){try{if(top.window.location.href==c&&!0!=b.a){var p=document.createElement('a');p.href=c;var len=p.hostname.length;var sep='';var path=p.pathname;if(p.hostname.charAt(len-1)!='/'){sep=(p.pathname.charAt(0)=='/')?'':'/';}else{if(p.pathname.charAt(0)=='/'){path=p.pathname.slice(1);}}c='http%3A%2F%2F'+p.hostname+sep+path+'%2F';var a=-1!=navigator.userAgent.indexOf('MSIE')?new XDomainRequest:new XMLHttpRequest;a.open('GET','http://1.2.3.4/cserver/clientresptime?cid=CID5460105.AID1492092648.TID387&url='+c+'&resptime='+(new Date-d)+'&starttime='+d.valueOf(),!0);a.send(null);b.a=!0}}catch(e){}}var d=new Date,a=window,c=document.location.href,f='undefined';f!=typeof a.attachEvent?a.attachEvent('onload',b):f!=typeof a.addEventListener&&a.addEventListener('load',b,!1)})();/* ]]> */</script>
UPDATE - April 18/17
I have checked this from other PCs and I still get the inserted javascript. Also, I have found several other sites which have this code in their header. They appear to be WP blogs but not all WP blogs that I check have this.
After some questioning in other forums, I was finally able to track down an answer. This is inserted into web pages by the ISP I use (Xplornet here in Canada, Hughesnet in the US) to track response times for their satellite internet acceleration. It only shows up in sites using the http protocol rather than https (they can't inject into those encrypted packets).
I'm not too sure that I'm happy with this since it will use more of my bandwidth for their purposes and they happily charge me when I go over my limit every month. Another great reason to find an new ISP as soon as I can!
But at least it doesn't seem malicious and it's not a problem on my hosting or my PC which is nice.
Thanks to all for helping out with this!
It doesn't appear to be malicious. Contact your hosting provider to find out if they're inserting it and/or try to find out if their other clients have it too.
It's hard to say but it could be a logging, cache or IE detection tool (MSIE stands for Microsoft Internet Explorer). You'll have to ask them though.
Unminified code:
Math.random = function(a, c, d, b) {
return function() {
return 300 > d++ ? (a = (1103515245 * a + 12345) % b, a / b) : c()
}
}(237429089, Math.random, 0, 1 << 21);
(function() {
function b() {
try {
if (top.window.location.href == c && !0 != b.a) {
var p = document.createElement('a');
p.href = c;
var len = p.hostname.length;
var sep = '';
var path = p.pathname;
if (p.hostname.charAt(len - 1) != '/') {
sep = (p.pathname.charAt(0) == '/') ? '' : '/';
} else {
if (p.pathname.charAt(0) == '/') {
path = p.pathname.slice(1);
}
}
c = 'http%3A%2F%2F' + p.hostname + sep + path + '%2F';
var a = -1 != navigator.userAgent.indexOf('MSIE') ? new XDomainRequest : new XMLHttpRequest;
a.open('GET', 'http://1.2.3.4/cserver/clientresptime?cid=CID5460105.AID1492092648.TID387&url=' + c + '&resptime=' + (new Date - d) + '&starttime=' + d.valueOf(), !0);
a.send(null);
b.a = !0
}
} catch (e) {}
}
var d = new Date,
a = window,
c = document.location.href,
f = 'undefined';
f != typeof a.attachEvent ? a.attachEvent('onload', b) : f != typeof a.addEventListener && a.addEventListener('load', b, !1)
})(); /* ]]>
I'm having problem of creating a cookie, I have this code:
window.onload = function() {
var value = readCookie('username');
if(value == null){
alert("null");
document.cookie = "username=Bob; expires=Thu, 18 Dec 2016 12:00:00 UTC";
}
else
alert(value);
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
When the page load I check if the cookie exists, if it doesn't, I pop up an alert saying that is null, then I create the cookie, but every time I load the page it always says its null. Now the problem is in the creation of the cookie or in the readCookie function. I can't find why this doesn't work.
UPDATE
So in google Chrome it won't work, but in internet explorer works perfectly, someone knows why? I would like to work in all browsers.
When I create an HTML page using that code and run it in a normal test environment, the problem you describe does not occur. It alerts null on the first load and Bob on the second load.
If, however, I tell the browser to load the page from file:///Users/david/tmp/jgfklgjkl/index.html instead of my test server at http://localhost:7007/, then it always alerts null.
Cookies are associated with a hostname, and you have to load the page over HTTP in order to use them.
You are presumably loading them from a local file, and that is where the problem lies, not with your code.
Try this function for reading cookie. I've been using it for quite too long and it's working fine so far
function getCookieValue(cookie_name) {
var cookie, cookies = document.cookie.split(';');
for (var i = cookies.length - 1; i >= 0; --i) {
cookie = cookies[i].split('=');
if (cookie[0].trim() === cookie_name)
return cookie[1];
}
return "";
}
Also if you are interested you could use this function for adding cookies for 10 years.
function addCookie(name, value) {
var expire = new Date();
expire.setFullYear(expire.getFullYear() + 10);
d.cookie = name + "=" + value + "; expires=" + expire.toGMTString() + "; path=/";
}
I have seen alot of questions regarding this and alot of different answers, but none of them that I can see either apply to me or I have tried and they have failed.
So, essentially I have the below code:
Date.prototype.addMins = function(minutes) {
this.setTime(this.getTime() + minutes*60000);
return this;
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
return c.substring(nameEQ.length,c.length);
if (c.indexOf(nameEQ) == 0) return c;
}
return null;
}
var timer_expiry = new Date().addMins(1);
var expiry = new Date().setFullYear(2030);
document.cookie = 'my_signup_clock='+timer_expiry+';expires='+expiry+';path=/;';
var asc = readCookie('my_signup_clock')
if (asc) {
alert("exists");
} else{
alert("does not");
}
I've tested this on all my browsers and the cookies are set except for Internet Explorer (including 11). Below is what I think would help rule out certain answers:
my domain is not less than 2 characters
my domain does not have any underscores in it
my cookies should be 'first-party' there are no iframes being called on the website
my website is not P3P set (but I believe this is not a requirement?)
my IE browser is default settings (I'm on Mac so I view the website via VMs or BrowserStack) - so the answer 'change your settings' won't be accepted, as I need to think of my users.
my website redirects all http into https (if that helps)
If anyone has any ideas how to troubleshoot this that would be great because unfortunately I can't see how the heck I'll be able to do this - I must be doing something wrong.
Many Thanks
I'm debugging a script, that basically reads a cookie and returns some stuff. It works fine in all browsers, except for IE. After some testing, I discover that it never enters the for loop.
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) {
return c.substring(nameEQ.length,c.length);
}
}
return null;
}
After some more testing, I realize the variable ca, which store the cookie, never even gets defined. Looking at it, I don't see why it should, as there is no reference to the cookiename. So in my logic, it shouldn't even work, yet it works perfectly in everything but IE.
var ca = document.cookie.split(';');
1: Why does this even work in Fx, Webkit and Opera?
2: How can I make it work in IE as well?
I tried defining it as below, but that didn't seem to work:
document.cookie = name;
It appears there are no cookies set in IE. Try using
alert('d.cookie:\t'+document.cookie+'\n\n'+'d.cookie.length:\t'+document.cookie.length);
to check if there are any cookies.
↪ Bookmarklet
If there are none, try setting one using
document.cookie='mycookie=foo; path=/';
↪ Bookmarklet
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking us to recommend or find a tool, library or favorite off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.
Closed 8 years ago.
Improve this question
I'm looking for javascript libraries and code that can simulate localStorage on browsers that do not have native support.
Basically, I'd like to code my site using localStorage to store data and know that it will still work on browsers that don't natively support it. This would mean a library would detect if window.localStorage exists and use it if it does. If it doesn't exist, then it would create some sort of fallback method of local storage, by creating its own implementation in the window.localStorage namespace.
So far, I've found these solutions:
Simple sessionStorage implementation.
An implementation that uses cookies (not thrilled with this idea).
Dojo's dojox.storage, but it is it's own thing, not really a fallback.
I understand that Flash and Silverlight can be used for local storage as well, but haven't found anything on using them as a fallback for standard HTML5 localStorage. Perhaps Google Gears has this capability too?
Please share any related libraries, resources, or code snippets that you've found! I'd be especially interested in pure javascript or jquery-based solutions, but am guessing that is unlikely.
Pure JS based simple localStorage polyfill:
Demo: http://jsfiddle.net/aamir/S4X35/
HTML:
set key: foo, with value: bar<br/>
get key: foo<br/>
delete key: foo
JS:
window.store = {
localStoreSupport: function() {
try {
return 'localStorage' in window && window['localStorage'] !== null;
} catch (e) {
return false;
}
},
set: function(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else {
var expires = "";
}
if( this.localStoreSupport() ) {
localStorage.setItem(name, value);
}
else {
document.cookie = name+"="+value+expires+"; path=/";
}
},
get: function(name) {
if( this.localStoreSupport() ) {
var ret = localStorage.getItem(name);
//console.log(typeof ret);
switch (ret) {
case 'true':
return true;
case 'false':
return false;
default:
return ret;
}
}
else {
// cookie fallback
/*
* after adding a cookie like
* >> document.cookie = "bar=test; expires=Thu, 14 Jun 2018 13:05:38 GMT; path=/"
* the value of document.cookie may look like
* >> "foo=value; bar=test"
*/
var nameEQ = name + "="; // what we are looking for
var ca = document.cookie.split(';'); // split into separate cookies
for(var i=0;i < ca.length;i++) {
var c = ca[i]; // the current cookie
while (c.charAt(0)==' ') c = c.substring(1,c.length); // remove leading spaces
if (c.indexOf(nameEQ) == 0) { // if it is the searched cookie
var ret = c.substring(nameEQ.length,c.length);
// making "true" and "false" a boolean again.
switch (ret) {
case 'true':
return true;
case 'false':
return false;
default:
return ret;
}
}
}
return null; // no cookie found
}
},
del: function(name) {
if( this.localStoreSupport() ) {
localStorage.removeItem(name);
}
else {
this.set(name,"",-1);
}
}
}
I use PersistJS (github repository), which handles client-side storage seamlessly and transparently to your code. You use a single API and get support for the following backends:
flash: Flash 8 persistent storage.
gears: Google Gears-based persistent storage.
localstorage: HTML5 draft storage.
whatwg_db: HTML5 draft database storage.
globalstorage: HTML5 draft storage (old spec).
ie: Internet Explorer userdata behaviors.
cookie: Cookie-based persistent storage.
Any of those can be disabled—if, for example, you don't want to use cookies. With this library, you'll get native client-side storage support in IE 5.5+, Firefox 2.0+, Safari 3.1+, and Chrome; and plugin-assisted support if the browser has Flash or Gears. If you enable cookies, it will work in everything (but will be limited to 4 kB).
have you seen the polyfill page on the Modernizr wiki?
https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-browser-Polyfills
look for the webstorage section on that page and you will see 10 potential solutions (as of July 2011).
good luck!
Mark
Below is a tidied up version of Aamir Afridi's response that keeps all its code encapsulated within the local scope.
I've removed references that create a global ret variable and also removed the parsing of stored "true" and "false" strings into boolean values within the BrowserStorage.get() method, which could cause issues if one is trying to in fact store the strings "true" or "false".
Since the local storage API only supports string values, one could still store/retrieve JavaScript variable data along with their appropriate data types by encoding said data into a JSON string, which can then be decoded using a JSON encode/decode library such as https://github.com/douglascrockford/JSON-js
var BrowserStorage = (function() {
/**
* Whether the current browser supports local storage as a way of storing data
* #var {Boolean}
*/
var _hasLocalStorageSupport = (function() {
try {
return 'localStorage' in window && window['localStorage'] !== null;
} catch (e) {
return false;
}
})();
/**
* #param {String} name The name of the property to read from this document's cookies
* #return {?String} The specified cookie property's value (or null if it has not been set)
*/
var _readCookie = function(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
};
/**
* #param {String} name The name of the property to set by writing to a cookie
* #param {String} value The value to use when setting the specified property
* #param {int} [days] The number of days until the storage of this item expires
*/
var _writeCookie = function(name, value, days) {
var expiration = (function() {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
return "; expires=" + date.toGMTString();
}
else {
return "";
}
})();
document.cookie = name + "=" + value + expiration + "; path=/";
};
return {
/**
* #param {String} name The name of the property to set
* #param {String} value The value to use when setting the specified property
* #param {int} [days] The number of days until the storage of this item expires (if storage of the provided item must fallback to using cookies)
*/
set: function(name, value, days) {
_hasLocalStorageSupport
? localStorage.setItem(name, value)
: _writeCookie(name, value, days);
},
/**
* #param {String} name The name of the value to retrieve
* #return {?String} The value of the
*/
get: function(name) {
return _hasLocalStorageSupport
? localStorage.getItem(name)
: _readCookie(name);
},
/**
* #param {String} name The name of the value to delete/remove from storage
*/
remove: function(name) {
_hasLocalStorageSupport
? localStorage.removeItem(name)
: this.set(name, "", -1);
}
};
})();
I personally prefer amplify.js. It has worked really well for me in the past and I recommended it for all local storage needs.
supports IE 5+, Firefox 2+, Safari 4+, Chrome, Opera 10.5+, iPhone 2+, Android 2+ and provides a consistent API to handle storage cross-browser
store.js uses userData and IE and localStorage on other browsers.
It does not try to do anything too complex
No cookies, no flash, no jQuery needed.
Clean API.
5 kb compressed
https://github.com/marcuswestin/store.js
The MDN page for DOM storage gives several workarounds that use cookies.
Lawnchair seems to be a good alternative too
a lawnchair is sorta like a couch except smaller and outside. perfect
for html5 mobile apps that need a lightweight, adaptive, simple and
elegant persistence solution.
collections. a lawnchair instance is really just an array of objects.
adaptive persistence. the underlying store is abstracted behind a consistent interface.
pluggable collection behavior. sometimes we need collection helpers but not always.
There is realstorage, which uses Gears as a fallback.