There is a cool Firefox extension which lets you export all cookies to a Netscape HTTP Cookies File, cookies.txt, which you can then use with wget (et.al.)
Here is an example cookies.txt file for the happycog.com site:
# Netscape HTTP Cookie File
# http://www.netscape.com/newsref/std/cookie_spec.html
# This is a generated file! Do not edit.
cognition.happycog.com FALSE / FALSE 1345696044 exp_last_visit 998800044
cognition.happycog.com FALSE / FALSE 1345696044 exp_last_activity 1314160044
How can I build the same style "cookies export" with Javascript? Granted it would only be able to read cookies for the current domain. That would be just fine.
Additional Details:
I realize that cookies can't be exported to the file system with pure javascript. I'd be happy with them being exported to a textarea, or with document.write. I just want to know how I can get them in the same format where I can basically copy and paste them to a cookies.txt file. The challenge here is to do it with javascript, though, and not to use an addon.
var cookieData = document.cookie.split(';').map(function(c) {
var i = c.indexOf('=');
return [c.substring(0, i), c.substring(i + 1)];
});
copy(JSON.stringify(JSON.stringify(cookieData)));
This will export your cookies into an array of key/value pairs (eg. [ [key1, val1], [key2, val2], ...]), and then copy it to your clipboard. It will not retain any expiration date info because that's impossible to extract via Javascript.
To import the cookies back, you'd run the following code:
var cookieData = JSON.parse(/*Paste cookie data string from clipboard*/);
cookieData.forEach(function (arr) {
document.cookie = arr[0] + '=' + arr[1];
});
Sorry about the delayed response - had to sleep. I have just been playing with this and concluded that the answer is NO.
The reason for this is that Javascript does not have access to any more information than the cookie's name and value, you can't retrieve the path, expiry time, etc etc. What do you actually want to do? Is this for one specific site you are developing or just for general use when browsing?
All cookies for the page is stored in document.cookie
Related
I am trying to set/get an array as a cookie in Javascript as follows:
let features = [];
for(const property in object) {
...
let feature = new Feature(...);
features.push(feature);
}
cookie.set('features', JSON.stringify(features));
console.log(JSON.parse(cookie.get('features')));
and I get the following error:
VM21081:1 Uncaught SyntaxError: Unexpected token u in JSON at position 0
P.S. If I do not use stringify/parse the result is undefined.
Could you help me, please?
Thank you in advance.
the issue is that you try to set and get cookies in the browser on the local environment.
I copied from the answer in this topic (Why does Chrome ignore local jQuery cookies?)
'Chrome doesn't support cookies for local files (or, like Peter Lyons mentioned, localhost*) unless you start it with the --enable-file-cookies flag. You can read a discussion about it at http://code.google.com/p/chromium/issues/detail?id=535.
*Chrome does support cookies if you use the local IP address (127.0.0.1) directly. so in the localhost case, that could be an easier workaround.'
to test your code you can use w3school editor, here is an example:
https://www.w3schools.com/code/tryit.asp?filename=GHTVNK8POVWM
(click run button to see the result)
I am trying to store in a cookie the state of a certain element on my page, more precisely the expanded or shrunk state of a sidebar.
I have managed to store it properly and it works, but I've noticed that if I refresh the page and toggle the sidebar from the expanded or shrunk state, there is a second cookie added, with the same name, but a new value.
Here is what the log outputs:
expanded=false; expanded=true; PHPSESSID=2314324545
I needed the cookie so that if the user wanted to go on another page, he could see the sidebar the way he left it in the previous page. Now if I have 2 cookies with the same name, this raises a problem when I am checking its value.
Here is how I have implemented it:
$('.expand-button').on('click', function(e) {
$('.pushmenu').toggleClass('expanded');
$('.navbar-left').toggleClass('expanded');
$('.navbar-left-2').toggleClass('small')
if( $(window).width()+scrollbarWidth > 1240){
$('.container.fluid-content').toggleClass('shrinked')
}
if($('.pushmenu').hasClass('expanded')) {
expandedValue = true;
document.cookie = 'expanded=' + expandedValue;
console.log(document.cookie);
} else {
expandedValue = false;
document.cookie = 'expanded=' + expandedValue;
console.log(document.cookie);
}
})
$(window).on('load', function() {
//cookie is already set
console.log(document.cookie);
if( document.cookie.indexOf('expanded=true') != -1 ) {
$('.pushmenu').toggleClass('expanded');
$('.navbar-left').toggleClass('expanded');
$('.navbar-left-2').toggleClass('small')
if( $(window).width()+scrollbarWidth > 1240){
$('.container.fluid-content').toggleClass('shrinked')
}
} else {
console.log('not doing anything');
}
})
Cookies are linked to the path and the domain name. You may receive two (or more!) cookies on the server side if each have a different domain name such as:
.domain.org
.www.domain.org
The order in which you receive the cookies is the least qualified domain name to the most qualified domain name (as shown in that list.)
I suggest you install FireBug (assuming you are using a FireBug compatible browser such as Firefox) and have a look at the cookies in there. You will see the details such as the path and domain name and also the expiration date.
To set the path, just use something like this:
blah=value; Path=/
Similarly, you can force the domain with:
blah=value; Domain=.domain.org
You may specify multiple parameters by separating them by semi-colons:
blah=value; Path=/; Domain=.domain.org
If you are using HTTPS (secure domain), I strongly advice you use Secure too:
blah=value; Path=/; Domain=.domain.org; Secure
Using FireBug, you can delete some of the cookies. It is up to you to do that, use the first version (.domain.org) or the last (.www.domain.org).
The discrepancy may come from your front end code (JavaScript) AND your backend code (your PHP). One way to see what your server returns, to see whether the Path and Domain are both specified as expected, is to use wget with the -S command line option:
wget -S http://domain.org
wget -S http://www.domain.org
If you allow both "" and "www", then you must force the domain without the www:
; Domain=.domain.org
Otherwise you will get those duplicates.
I'm very new to JMeter and need your help on how to modify a cookie.
Here is the scenario:
I'm testing an assessment/test taking website that offers multiple answers to questions. When a user makes his selections and hits the submit button, the JavaScript in the page appends his answers (e.g., "Answers = BBAACDA...") to the cookie and makes the next GET request (instead of a POST request!).
Since, JMeter does not execute JavaScript (as popularly mentioned in its manual - it's not a browser), it cannot append the answers to the cookie. As a result, my test plan fails to recognize user interaction.
How can I add/append/modify a dynamic cookie? Thanks in advance!
--Ishti
Use a Beanshell pre-processor or better a Jsr223 Pre-Processor with groovy and use code mentionned here:
http://javaworks.wordpress.com/2011/08/05/setting-cookie-in-jmeter/
Code:
import org.apache.jmeter.protocol.http.control.CookieManager;
import org.apache.jmeter.protocol.http.control.Cookie;
CookieManager manager = sampler.getCookieManager();
Cookie cookie = new Cookie("<NAME>","<VALUE>","<HOST>","/",false,0);
manager.add(cookie);
I had to implement some changes in the code that worked for me:
import org.apache.jmeter.protocol.http.control.CookieManager;
import org.apache.jmeter.protocol.http.control.Cookie;
CookieManager manager = ctx.getCurrentSampler().getCookieManager();
Cookie cookie = new Cookie("<NAME>","<VALUE>","<DOMAIN>","<PATH>",false,0, true, true, 0);
manager.add(cookie);
Following the definition in http://jmeter.apache.org/api/org/apache/jmeter/protocol/http/control/Cookie.html
It is possible to modify or add a cookie manually in a groovy pre-processor script in the same way as https://stackoverflow.com/a/38505077/5747304.
Here's how to find and edit a cookie by browsing all cookies in the cookie manager:
import org.apache.jmeter.protocol.http.control.CookieManager;
import org.apache.jmeter.protocol.http.control.Cookie;
log.info("#########################################################################");
// cookie manager
CookieManager manager = ctx.getCurrentSampler().getCookieManager();
def NbOfCookies = manager.getCookieCount();
for (def i = 0; i < NbOfCookies; i++) {
log.info("Cookie n° " + (i+1) + ": " + manager.get(i).getName() + ": " + manager.get(i).getValue());
if (manager.get(i).getName() == "Cookie_name_to_find") {
log.info("MAJ of Cookie_name_to_find");
manager.get(i).setValue("New_cookie_value");
log.info("-> " + manager.get(i).getName() + ": " + manager.get(i).getValue());
}
}
log.info("#########################################################################");
Here is the list of cookie manager methods like add or delete ...: http://jmeter.apache.org/api/org/apache/jmeter/protocol/http/control/CookieManager.html.
Here is the list of cookie methods to modify more properties like the domain, its expiration date ...: http://jmeter.apache.org/api/org/apache/jmeter/protocol/http/control/Cookie .html
It should be known that according to the standart chosen in the cookie manager, the manually modified values can still be modified by the manager before the request so you have to be careful.
I have set a session in PHP, which is creating a cookie: PHPSESSID...
I can detect this in Chrome & Opera by using document.cookie. However in Forefox, document.cookie also returns cookies set on the page by other domains, e.g. Google Analytics.
In PHP I am setting the sessions like:
session_start();
$_SESSION['source'] = &$ref['source'];
$_SESSION['term'] = &$ref['term'];
session_write_close();
I need to be able to detect if this session is set in Javascript, by locating the cookie. What is the best way to go about this?
At the moment I am just using:
document.cookie.indexOf( 'PHPSESSID' )
which seems like a bit of a botch.
The document.cookie property will return all the cookies. While your indexOf will work, it will break if your cookies actual data contains 'PHPSESSID'. It will also match the following cookie 'MYPHPSESSIDIDIT', as it contains your cookie name.
You could parse the cookies with the following function (not tested):
function getCookieValue(name)
{
// find cookie entry in middle?
var s=document.cookie,
c=s.indexOf("; "+name+"=");
if(c==-1)
{
// no, is it at the start?
c=s.indexOf(name+"=");
if(c!=0) return null;
}
// get length of value
var l=c+name.length+1,
e=s.indexOf(";",l);
// is it at the end?
if(e==-1) e-s.length;
// cut out the value
return s.substring(l,e);
}
Hope this helps
Use this Jquery plugin, it's so cool.
https://github.com/carhartl/jquery-cookie
You can use it like this way:
if($.cookie('PHPSESSID') != undefined){
//PHPSESSID exists
}
I am trying to make a hta (html application) where you can add names to an array, and then find out if a certain name is in the array. When I close and reopen the hta (or refresh for a html), none of the names are saved. How do I make it so that when I run the function for adding a name, the code saves with the variable having the name in it.
this is the function for adding a name
var names = []
function addName(first, last){
names.push(first + " " + last)
}
function realAddName(eventObject){
var addFirstName = document.getElementById("addFirstName")//the input box for the first name
var addLastName = document.getElementById("addLastName")//the input box for the last name
addName(addFirstName.value, addLastName.value)
alert("The name you input is now added to the thing.")
}
I don't have jQuery, so do not give me answers that use jQuery.
Please Help Me.
That's now how javascript works. When the browser is closed any values that you'ved added to the array do not get saved. This is the role of the database. jQuery wouldn't be able to accomplish this either.
Local storage maybe will help you. For example:
function addName(first, last) {
localStorage.setItem("usr123", first + " " + last)
}
You can add, change, or remove your data in local storage. But it's limited. You can find out more about localStorage here: HTML5 Web Storage
You need to persist your application's state to disk. Because this is a HTA it means you can use Scripting.FileSystemObject to interact with the local filesystem.
var fs = new ActiveXObject("Scripting.FileSystemObject");
var textFile = fs.CreateTextFile("foo.txt");
textFile.WriteLine(someVariable);
textFile.Close();
fs is an object that gives you access to the local filesystem: FileSystemObject
FileSystemObject has a method called CreateTextFile that creates a new textfile on disk and gives you an object (textFile) you can use to write text to this file.
WriteLine writes some text to the file
.Close() causes the textfile to be "saved" safely.
user2216996
If you really need to ask then you don't need a database for what you are doing. Try the "Hey, Scripting Guy!" solution at http://blogs.technet.com/b/heyscriptingguy/archive/2007/11/09/hey-scripting-guy-how-can-i-save-information-in-an-hta-as-a-tab-separated-values-file.aspx
If you really want to learn about databases then I suggest that you go to http://en.wikipedia.org/wiki/Database and start reading.