导出 Cookies

一键导出多种格式的 Cookies!

  1. // ==UserScript==
  2. // @name Export Cookies
  3. // @name:zh-CN 导出 Cookies
  4. // @namespace http://tampermonkey.net/
  5. // @version 0.1.0
  6. // @description Export cookies to various formats in one click!
  7. // @description:zh-CN 一键导出多种格式的 Cookies!
  8. // @author PRO-2684
  9. // @match *://*/*
  10. // @run-at context-menu
  11. // @license gpl-3.0
  12. // @grant GM_registerMenuCommand
  13. // @grant GM.cookie
  14. // @grant GM.download
  15. // ==/UserScript==
  16.  
  17. (function () {
  18. "use strict";
  19. const log = () => { };
  20. // const log = console.log.bind(console, `[${GM.info.script.name}]`);
  21. // Adapted from https://github.com/kairi003/Get-cookies.txt-LOCALLY/blob/master/src/modules/cookie_format.mjs
  22. function jsonToNetscapeMapper(cookies) {
  23. return cookies.map(({ domain, expirationDate, path, secure, name, value }) => {
  24. const includeSubDomain = !!domain?.startsWith('.');
  25. const expiry = expirationDate?.toFixed() ?? '0';
  26. const arr = [domain, includeSubDomain, path, secure, expiry, name, value];
  27. return arr.map((v) => (typeof v === 'boolean' ? v.toString().toUpperCase() : v));
  28. });
  29. };
  30. const formats = {
  31. netscape: {
  32. ext: '.txt',
  33. mimeType: 'text/plain',
  34. serializer: (cookies) => {
  35. const netscapeTable = jsonToNetscapeMapper(cookies);
  36. const text = [
  37. '# Netscape HTTP Cookie File',
  38. '# http://curl.haxx.se/rfc/cookie_spec.html',
  39. '# This file was generated by Export Cookies! Edit at your own risk.',
  40. '',
  41. ...netscapeTable.map((row) => row.join('\t')),
  42. '' // Add a new line at the end
  43. ].join('\n');
  44. return text;
  45. }
  46. },
  47. json: {
  48. ext: '.json',
  49. mimeType: 'application/json',
  50. serializer: JSON.stringify
  51. }
  52. };
  53. async function blobCookies(format) {
  54. const { mimeType, serializer } = formats[format];
  55. const cookies = await GM.cookie.list({});
  56. log("Extracted cookies:", cookies);
  57. const text = serializer(cookies);
  58. log("Serialized cookies:", text);
  59. const blob = new Blob([text], { type: mimeType });
  60. return URL.createObjectURL(blob);
  61. }
  62. const result = confirm('Please select the format you want to export the cookies in.\n\nPress OK to export in Netscape format (.txt), or press Cancel to export in JSON format (.json).');
  63. const format = result ? 'netscape' : 'json';
  64. blobCookies(format).then((blob) => {
  65. GM.download(blob, `cookies${formats[format].ext}`).then(() => {
  66. URL.revokeObjectURL(blob);
  67. console.log(`Cookies exported in ${format.toUpperCase()} format.`);
  68. }).catch((err) => {
  69. console.error('Failed to download the cookies.', err);
  70. });
  71. });
  72. })();