Save cookies with javascript how to specify domain? - javascript

I'm using this code to save cookies:
function saveCookie(name,value) {
var date = new Date();
date.setTime(date.getTime()+(60*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
document.cookie = name+"="+value+expires+"; path=/";
}
My problem is that it saves the cookie with domain "example.com" and I want to write them to ".example.com" so I can also read them from subdomains. This is easy to do with PHP but I don't know how to do it with javascript. How can I add a dot before the domain when I save the cookie?

You already have path in there, domain is specified in the same way.

To permit reading from other sub-domains, try:
'; path=/; domain=.'+window.location.host;

Related

How do I add a path to a cookie function?

I am having some trouble adding the path of "/" to my cookie, which is set with a function.
function WriteCookie(){
if(document.part1.pn1.value==""){
return;
}
var cookievalue=escape(document.part1.pn1.value) + ";";
document.cookie="partnumber1=" + cookievalue;
I'm sure it is a very simple answer, but I just can't seem to get it to work.
I have tried something like:
function WriteCookie(){
if(document.part1.pn1.value==""){
return;
}
var cookievalue=escape(document.part1.pn1.value) + ";";
document.cookie="partnumber1=" + cookievalue + path=/;
But clearly this is not correct.
This is the answer you need:
document.cookie = name+"="+value+expires+"; path=/";
If you set path=/ the cookie is available for the whole domain. Otherwise, your cookie is saved just for the current page you can't access it on another page.
For more info read- http://www.quirksmode.org/js/cookies.html - review the Domain and path section

Create Constant Cookie

The situation is the next: We have a site that have a lot of domains:.pl,de,com,se... This domeins are only on home page and landing pages. After you make search it is redirecting it on .com domain. So all domains become COM. I need something to create in Google Tag Manager that will remember the first domain (pl,de,com,se and annother) and will hold that information for all the path. So if I will have such information I could exactly indicate to my Adwords tracking codes which code has to fire. I am working with cookies in Google Tag Manager. How to create the cookie that will change only in the situation when the tag with the cookie will fire. I need the cookie that holds the information from one page - not changing with the new page. The code I use is:
<script>
function createCookie(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 = "";
document.cookie = name+"="+value+expires+"; path=/";
}
createCookie("DomainCookie",{{Page URL}})
</script>

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.

Issue with cookie, cookie is lost after closing browser

I've created a cookie like below and can retrieve all font_size, back_color and font_name. But once I close the browser the cookie is lost. From what I know is if we get expiry date wrong cookie can be lost but I've tested the date, expireGMT and is fine. Have I done anything wrong in the code below? Do I need to include path as well?
document.cookie = "font_size=14";
document.cookie = "back_color=Gray";
document.cookie = "font_name=Georgia";
document.cookie = "expires=" + expireGMT;
Each individual write to document.cookie is the setting of a cookie, and any options (including that cookie's expiration date) must be set on that write. You need to include the expiring time on every cookie assignment:
document.cookie = "font_size=14; expires=" + expireGMT;
document.cookie = "back_color=Gray; expires=" + expireGMT;
document.cookie = "font_name=Georgia; expires=" + expireGMT;
without that, each cookie will be created as session cookies and expire when the browser's closed.

How do I set the HttpOnly flag of a cookie with javascript?

I'm trying to create a cookie, with the HttpOnly flag enabled.
While there seems to be a plethora of resources about how to do it in Java and .Net, I need to do it in javascript.
Here is my (currently failing) function
createCookie = 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 = "";
document.cookie = name+"="+value+expires+"; domain=my.domain.com; path=/; HttpOnly;";
Thanks -
You cannot access an HttpOnly cookie in JavaScript.
The following quotation is borrowed from the Wikipedia material:
The HttpOnly cookie is supported by most modern browsers. On a supported browser, an HttpOnly session cookie will be used only when transmitting HTTP (or HTTPS) requests, thus restricting access from other, non-HTTP APIs (such as JavaScript).
In other words, HttpOnly cookies are made to be used only on the server side.
I wrote an example in PHP:
<?php
$name = 'foo';
$value = 'bar';
$expirationTime = 0; // Session cookie.
$path = '/';
$domain = 'localhost';
$isSecure = false;
$isHttpOnly = false;
setcookie($name, $value, $expirationTime, $path, $domain, $isSecure, $isHttpOnly);
?>
<script>
alert(document.cookie);
</script>
It alerts foo=bar.
Remove the cookie, change $isHttpOnly to true, reload the page, and you'll see an empty alert. But at the same time the browser stores the cookie to send it during a request to the server.

Categories