Skip to content

Instantly share code, notes, and snippets.

@clochix
Created July 10, 2013 16:48
Show Gist options
  • Star 21 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save clochix/5967978 to your computer and use it in GitHub Desktop.
Save clochix/5967978 to your computer and use it in GitHub Desktop.
Sample cookies management with CasperJS: functions to load cookies from a Netscape formatted file and save them
/**
* Load cookies from a file
*
* @param {String} file name of da file.
*
* @return {Array} of cookies.
*/
function loadCookies(file) {
"use strict";
var cookies = [];
if (fs.exists(file)) {
cookies = fs.read(file).split("\r\n");
cookies.forEach(function (cookie) {
var detail = cookie.split("\t"),
newCookie = {
'name': detail[5],
'value': detail[6],
'domain': detail[0],
'path': detail[2],
'httponly': false,
'secure': false,
'expires': (new Date()).getTime() + 3600 * 24 * 30 /* <- expires in 1 month */
};
phantom.addCookie(newCookie);
});
} else {
this.log("Unable to load cookies from " + file + ". File doesn't exist", "warning");
}
return cookies;
};
/**
* Save cookies to a file
*
* @param {String} file name of da file.
*/
function saveCookies(file) {
"use strict";
var res = '';
this.page.cookies.forEach(function (cookie) {
res += utils.format("%s\t%s\t%s\t%s\t%s\t%s\t%s\r\n", cookie.domain, 'TRUE', cookie.path, 'FALSE', cookie.expiry, cookie.name, cookie.value);
});
fs.write(file, res, 'w');
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment