Cookie Editor

编辑cookies

  1. // ==UserScript==
  2. // @name Cookie Editor
  3. // @version 1.0
  4. // @description 编辑cookies
  5. // @author DeepSeek
  6. // @match *://*/*
  7. // @grant GM_registerMenuCommand
  8. // @run-at document-end
  9. // @namespace https://greasyfork.org/users/452911
  10. // ==/UserScript==
  11.  
  12. (function() {
  13. 'use strict';
  14.  
  15. // 注册菜单命令
  16. GM_registerMenuCommand('编辑Cookies', editCookiesPrecisely, 'e');
  17.  
  18. function editCookiesPrecisely() {
  19. // 获取当前所有cookie并转换为对象
  20. const currentCookies = document.cookie.split(';').reduce((obj, cookie) => {
  21. const [name, value] = cookie.trim().split('=');
  22. if (name) obj[name] = value || '';
  23. return obj;
  24. }, {});
  25.  
  26. // 转换为编辑字符串(分号分隔)
  27. const editText = Object.entries(currentCookies)
  28. .map(([name, value]) => `${name}=${value}`)
  29. .join('; ');
  30.  
  31. // 使用prompt弹窗编辑
  32. const newText = prompt('编辑Cookies(分号分隔格式):\n\n注意:任何不在编辑框中的cookie将被删除', editText);
  33. if (newText === null) return; // 用户取消
  34.  
  35. try {
  36. // 解析新cookie
  37. const newCookies = newText.split(';').reduce((obj, cookie) => {
  38. const [name, value] = cookie.trim().split('=');
  39. if (name) obj[name] = value || '';
  40. return obj;
  41. }, {});
  42.  
  43. // 找出需要删除的cookie(原有但不在新列表中的)
  44. Object.keys(currentCookies).forEach(name => {
  45. if (!(name in newCookies)) {
  46. document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/`;
  47. }
  48. });
  49.  
  50. // 设置新的或修改的cookie
  51. Object.entries(newCookies).forEach(([name, value]) => {
  52. document.cookie = `${name}=${value}; path=/`;
  53. });
  54.  
  55. // 显示结果并刷新
  56. const changedCount = Object.keys(newCookies).length;
  57. const deletedCount = Object.keys(currentCookies).length - changedCount;
  58. alert(`Cookie更新完成:\n新增/修改: ${changedCount}个\n删除: ${deletedCount}个\n页面将刷新...`);
  59. setTimeout(() => location.reload(), 500);
  60. } catch (e) {
  61. alert('错误: ' + e.message);
  62. }
  63. }
  64. })();