Unable to set cookie on Internet Explorer via Javascript - javascript

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

Related

HTML cookie don't create

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=/";
}

Conditional Cached Page Redirect

I am trying to set up a conditional cached re-direct depending on the website viewers choice.
Here's an example of how I am looking to have the website function ( you can test this by going to vonage.com):
When I visit www.vonage.com, I have a choice between "For Personal, For Small Business, For Mid-Market & Enterprise".
After making the choice, you'll be sent to the associated website/subdomain - either vonage.com, personal.vonage.com, or enterprise.vonage.com.
Then, if you try to go back to the initial page with choices, you won't be able to, you're redirected back to the choice that you've already made.
How is this done? I would like to implement something similar. I'm using Wordpress by the way, but that probably won't matter, I can get my hands dirty in the code or .htaccess.
There may be a better way, and this is java-script only not php, but a cookie should do the trick.
on page load check if the cookie exists, if it does redirect, if not don't:
if (document.cookie.indexOf("home") >= 0) {
// redirect them to home
}
else if (document.cookie.indexOf("business") >= 0) {
// redirect them to business
}
else if (document.cookie.indexOf("enterprise") >= 0) {
// redirect them to enterprise
}
if none of those trigger, and the user is not redirected when they choose an option set their cookie, for example:
// set a new cookie
expiry = new Date();
expiry.setTime(date.getTime()+(10*60*1000)); // Ten minutes
// Date()'s toGMTSting() method will format the date correctly for a cookie
document.cookie = "business; expires=" + expiry.toGMTString();
(function(href, referrer) {
var enterprise = "http://enterprise.mysite.com"
var personal = "http://personal.mysite.com"
var is_enterprise = new RegExp(enterprise).test(href)
var is_personal = new RegExp(personal).test(href)
var cache = readCookie('portal')
if (cache) return location.href = cache
var portal = is_enterprise || is_personal
if (portal) document.cookie = "portal=" + (enterprise || personal) + "; expires=Fri, 31 Dec 9999 23:59:59 GMT";
return null
})(location.href, document.referrer)
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;
}

localStorage not working in Edge?

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...');
}

Client-side JS session library

I'm looking for a client-side JS library to store session variables.
I'd like a library that supports alternative storage medium, e.g. cookies when available with fallback on other techniques.
For instance, I found this one (but the last update is in 2009):
http://code.google.com/p/sessionstorage/
I'm not interested in security (apart a bit of data isolation among applications), as I'm not going to store sensitive data.
To give an example of use case, I want to display a message "Chrome user? Download the app" for chrome users, and I'd like to maintain a status in session to avoid displaying the message again to the same user. I don't want server-side sessions as I have caching enabled, so I must be able to serve the exact same page to different users.
You can use localStorage if available, and if it's not, then using cookies (or whatever you feel to):
var appToken = createToken();
try {
if (localStorage.getItem) {
localStorage.downloadAppAlert = appToken;
} else {
setCookie('downloadAppAlert', appToken, 10); // name, a string value, num. of days
}
} catch(e) {
console.log(e);
}
Then you can use some function to set your cookies - i.e. this one i just found in w3schools:
function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}
To retrieve a cookie value by it's name - downloadAppAlert in the example - you can use the one on the w3schools link or something like 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);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
Also, to retrieve a previously setted item on the localStorage you simply:
var appToken = localStorage.getItem('downloadAppAlert');
EDIT: Sorry, with the hurries i forgot to mention what createToken() does. It is supposed to be a random alphanumeric generator function. You can find plenty on SO, like:
Random alpha-numeric string in JavaScript?
Generate random string/characters in JavaScript
Generating (pseudo)random alpha-numeric strings
Use node-client-sessions (https://github.com/mozilla/node-client-sessions) by mozilla.

Cookie always return null in IE

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

Categories