Skip to content

Instantly share code, notes, and snippets.

@sevaa
Created January 25, 2017 02:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sevaa/ac2f62f4e638ccbf3b5ec149d1261d85 to your computer and use it in GitHub Desktop.
Save sevaa/ac2f62f4e638ccbf3b5ec149d1261d85 to your computer and use it in GitHub Desktop.
CurlCookies
var sys = require("system"), fs = require("fs");
if(sys.args.length < 2)
{
console.log("ExportCurlCookies requires a parameter - cookie file name.");
phantom.exit(1);
}
var Dest = sys.args[1];
var f = fs.open(Dest, {mode:"w"});
f.writeLine("# Netscape HTTP Cookie File");
f.writeLine("# http://curl.haxx.se/docs/http-cookies.html");
f.writeLine("# This file was generated by libcurl! Edit at your own risk.");
f.writeLine("");
var i, n = phantom.cookies.length;
for(i=0;i<n;i++)
{
var Coo = phantom.cookies[i];
f.writeLine(
(Coo.httponly ? "#HttpOnly_" : "") + Coo.domain + "\t" +
(Coo.domain.substr(0, 1) == "." ? "TRUE\t" : "FALSE\t") +
Coo.path + "\t" +
(Coo.secure ? "TRUE\t" : "FALSE\t") +
Coo.expiry.toString() + "\t" +
Coo.name + "\t" +
Coo.value
);
}
f.close();
phantom.exit(0);
var sys = require("system"), fs = require("fs");
if(sys.args.length < 2)
{
console.log("ImportCurlCookies requires a parameter - cookie file name.");
phantom.exit(1);
}
var Src = sys.args[1];
if(!fs.isFile(Src))
{
console.log("Source file " + Src + " not found.");
phantom.exit(1);
}
Src = fs.read(Src, {mode:"r"}).split("\n");
var i, n = Src.length;
for(i=0;i<n;i++)
{
var l = Src[i].trim();
if(l.length && (l.substr(0, 1) != "#" || l.substr(0, 10) == "#HttpOnly_"))
{
var a = l.split("\t");
var HttpOnly = a[0].substr(0, 10) == "#HttpOnly_";
var Domain = HttpOnly ? a[0].substr(10) : a[0];
if(Domain.substr(0, 1) != ".")
Domain = "." + Domain;
var Expires = parseInt(a[4]) * 1000;
if(!Expires)
Expires = undefined;
if(phantom.addCookie(
{
name: a[5],
value: a[6],
domain: Domain,
path: a[2],
httponly: HttpOnly,
secure: a[3] == "TRUE",
expires: Expires
}))
{
console.log("Added " + a[5] + "@" + Domain);
}
else
{
console.log("Error adding " + a[5] + "@" + Domain);
}
}
}
phantom.exit(0);
@sevaa
Copy link
Author

sevaa commented Jan 25, 2017

Translating cookie files from PhantomJS format to cURL format and back.

The command line for PhantomJS to cURL conversion goes:
phantomjs --cookies-file=src.txt ExportCurlCookies.js dest.txt
And the command line for other way would go:
phantomjs --cookies-file=dest.txt ImportCurlCookies.js src.txt

The export script overwrites the destination file completely, doesn't add to it. The import script merges the file contents with the existing cookies.

Tested against PhantomJS 1.9.8.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment