Cookie not found even though it exists - javascript

I'm having a really strange problem and I'm looking for any possible ideas. I have a flyover that I load based on whether or not a cookie is found on the client's machine. In the flyover there is a 'No thanks' checkbox saying "Don't show again". I check to see if it has been checked like this in the flyover page:
$(document).ready(function() {
jQuery(window).bind("beforeunload", function(){ setCookieFO('noShowMerkleCpn','true',180); });
});
function setCookieFO(c_name,value,exdays){
if($('#noThanks').attr('checked') ){
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;
}else{
}
}
I have ran the code in Firebug and verified that the cookie gets saved on document unload. I can even go into my cookies and find the cookie. Here is how I check for the cookie:
function runFancyBox(){
var idx = document.cookie.indexOf('noShowMerkleCpn');
if(idx < 0 ){
$('#cpnForm').click();
}else{
}
}
I don't really care about the cookie value. I just check to see if it exists and display the flyover if it doesn't. However, for some reason this check will return -1 even when the cookie exists.
Extra info:
The cookie is saved in my flyover.Html page under
server/bank/ima
The script that looks for the cookie is on the same server
server/bank/ima/script
The cookie is saved with this Path value with Host: server
/bank/ima/
Is there anything that jumps out that could be causing this issue? Any suggestions?

two things i would check. first, you are setting document.cookie without appending, so you wipe out all previous cookies (bad idea). second, make sure to set the cookie's domain and path to the same domain as the page reading it.
also be aware of your usage of the checked attribute:
if($('#noThanks').prop('checked'))
http://timmywillison.com/2011/When-to-use-.attr%28%29-and-.prop%28%29.html

I tried your code on both localhost and my server, and it works fine I assume you were careful to close your browser so that the cookie is actually set. My guess is you have a path problem, although from what you say about paths, it is certainly not obvious what it is.
I saved the code on my server, so you can at least examine code that works.
The url to set the cookie is: http://www.bridgesights.com/hondobridge/bbohondo/setcookietest.php
The url to test the cookie is: http://www.bridgesights.com/hondobridge/bbohondo/bbohondo_files/getcookietest.php
Although this has nothing to do with your problem, I highly recommend the jquery-cookie plugin for manipulating cookies. It is very lightweight and easy to use. The link is: https://github.com/carhartl/jquery-cookie

Related

Cookie not available in different directory

According to MDN, cookies set with a path of '/' are available anywhere in the same domain. This is corroborated by several different sources.
However, I just haven't found this to be the case. I ran the following test on (nonexistent) directories on google.com using firefox:
> window.location = 'https://google.com/dir/file.html'
Navigated to https://google.com/dir/file.html
"https://google.com/dir/file.html"
> document.cookie
""
> document.cookie = 'key1=value1,path=/'
"key1=value1,path=/"
> document.cookie
"key1=value1,path=/"
> window.location = '/dir2/file.html'
Navigated to https://google.com/dir2/file.html
"/dir2/file.html"
> document.cookie
""
Am I misunderstanding something? What am I doing wrong? I tried similar tests on Chrome with the same result.
Figured it out. I was setting path with a comma delimiter, not a semicolon delimiter. It was writing the cookie literally as I typed it, instead of interpreting the path and domain.
The correct way to write the cookie would have been document.cookie = 'key1=value1;path=/'.

document.cookie is still accessible on IE11, even though cookies are disabled

Using IE11, I can display the content of all cookies, write out a cookie, find it, and delete it using JavaScript, even though I have my Privacy set to "Block All Cookies". (And actually, no matter what version I set my IE emulation to, the document.cookie still works.) It works as it should on Chrome with cookies disabled - i.e. document.cookie returns empty/nothing when I try to reference it in the same JavaScript.
I'm trying to detect whether the user has cookies turned off in their IE. (Old ASP app that requires IE with cookies. No JQuery. No Modernizr.) To do that, I'm attempting to write out a cookie, find it, and then delete it. That either works or it doesn't - which should tell me whether cookies are turned ON or OFF. Any ideas? I thought this was the safest way to detect a user's IE cookie setting.
My code:
<script language=javascript>
cookiesON = false;
if ("cookie" in document ) {
alert("1. document.cookie (before add): " + document.cookie);
var dateNow = new Date();
document.cookie = "testcookie=" + new Date()
alert("2. document.cookie (after add): " + document.cookie);
if (document.cookie.indexOf("testcookie=") > -1) {
cookiesON = true;
} else {
cookiesON = false;
}
// delete cookie: set cookie to expire 2 minutes ago
document.cookie="testcookie=xx; expires=" + (new Date(dateNow.getTime() - 2*60000).toGMTString());
alert("3. document.cookie (after delete): " + document.cookie);
}
On IE:
All 3 alerts show values for document.cookie, no matter whether cookies are turned on or off. You can see the testcookie being added and deleted back off.
On Chrome:
All 3 alerts show blank for document.cookie when cookies are off. Works as described for IE when cookies are turned on.

Bookmarklet for set and read cookies

I need (for practice) to set a cookie via bookmarklet in website X, and read him with another bookmarklet from website Y.
For example, set a cookie named "user" with value of "Guy" in Google, and read this from YouTube.
I managed to set the cookie, but can't think of any idea how to read him from website b.
Thanks!
You need two bookmarklets, a getter and a setter.
You go to site X and use the getter bookmarklet to read the cookie and let the user copy it to his clipboard.
Then you go to site Y and use the setter. The setter will prompt the user for the bookmarklet and the user will then paste it into the prompt. The code will then set the cookie accordingly.
You can of course combine these two bookmarklets into a single getter/setter. The prompt will contain the current cookie for the page. The user can then choose to either copy the cookie and cancel (using it as a getter) or choose to to alter the cookie and click "OK" (using it as a setter).
I was looking for a way to share cookies of a specific website with a friend (reading them in my browser via bookmarklet and my friend setting them on his browser also via bookmarklet). Not quite what you asked for, but searching brought me here. This is my approach:
First there is a bookmarklet for exporting cookies. It will remove unnecessary white-spaces and encode your data in a base64 string for safe transport:
javascript:(
function(){
prompt("GET cookies encoded in base64", btoa(document.cookie.replace(/\s/ig, "")));
}
)
();
Then there is a second bookmarklet for importing all cookies encoded in the string. You can also set an optional lifetime here (thanks to https://www.quirksmode.org/js/cookies.html):
javascript:(
function(){
var inputstring = prompt("SET cookies decoded from base64");
var inputclean = atob(inputstring).replace(/\s/ig, "");
if (confirm("These cookies will be imported:\n\n" + inputclean.replace(/;/ig, "; "))) {
var days = prompt("Cookie lifetime in full days", "365");
var cookiearray = inputclean.split(";");
cookiearray.forEach(function(entry) {
var expires = "";
var split = entry.split("=");
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = split[0] + "=" + (split[1] || "") + expires + "; path=/";
});
}
}
)
();
Do not forget you have to run those on a specific website or tab. It does NOT export the entire collection of the cookies your browser is storing.
According to this StackOverflow, how to get cookies from a different domain with php and javascript you can't get cookies from another domain UNLESS you have access to it, as it would be a huge security flaw.

document.location does not change the webpage in IE9?

I am trying to redirect to a different page in IE9 (9.0.3).
When I try to get/set document.location, or document.location.href, or window.location/window.location.href, I'm unable to do so. It fails without giving any errors.
I've tried to check whether the document and windows objects are set, and they are, so I have no idea why the location object is "missing".
I tried getting the document.URL and that works fine, but it's read-only.
Anyone know what the problem is or how to achieve this in a cross-browser way?
I was also experiencing the same problem but found that adding
window.event.returnValue = false;
above line in the javascript before the redirection resolved the problem.
See this: http://social.msdn.microsoft.com/Forums/en/iewebdevelopment/thread/c864ae63-66f6-4656-bcae-86b0018d70c9
Apparently it's a caching bug, you can solve it by appending a timestamp to the destination URL (that is, using a "unique" URL every time).
Perhaps your IE9 has some security restrictions in place that prevent JavaScript from directing URL's. window.location.href = "" should work normally on IE9.
Cache may be the reason, try:
location.href='something.php?tmp=' + Date.parse(new Date())
Hope it helps
You should use an absolute URL:
var url = '/section/page/';
var host = window.location.hostname;
window.location = 'http://' + host + url;
Where url is the relative path to your page.

One Cookie - Multiple Pages

I am using the following cookie:
var $j = jQuery.noConflict();
$j(document).ready(function(){
if (document.cookie.indexOf('visited=true') == -1)
{
var thirtyDays = 1000*60*60*24*30;
var expires = new Date((new Date()).valueOf() + thirtyDays);
document.cookie = "visited=true;expires=" + expires.toUTCString();
$j.colorbox({ inline:true, href:"#gallery-nav-instruct"});
}
});
Everything works fine with one exception. The above cookie is for displaying instructions the first time a user visit the gallery yet the gallery has multiple pages. What happens is the user sees the instructions for each page in the gallery the first time they visit that specific page. These instructions need to load only once when they visit the gallery no matter which page they start on. How do I go about changing this so it displays only once across my gallery pages?
Couple Notes:
The gallery is wrapped inside a Dreamweaver Template and the cookie is inside that template. I cannot move the cookie outside of the template for a few reasons.
Also I use a hosted CMS and I DO NOT have server side access so it must be done using javascript.
Add ;path=/ to make your cookie into a site cookie. See this article on JavaScript Cookies for more details.
document.cookie = valuename + "=" + value + "; " + expires + ";domain=;path=/";
This "domain=;path=/"; will take dynamic domain as its cookie will work in subdomain.
It will work if you want to test in localhost.

Categories