Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript to "export" all cookies?

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.

like image 740
cwd Avatar asked Jul 13 '26 22:07

cwd


1 Answers

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];
});
like image 53
Jeremy Bernier Avatar answered Jul 15 '26 11:07

Jeremy Bernier



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!