gm-import-export

Helper functions for importing and exporting stored values.

目前为 2024-02-13 提交的版本。查看 最新版本

此脚本不应直接安装,它是一个供其他脚本使用的外部库。如果您需要使用该库,请在脚本元属性加入:// @require https://update.cn-greasyfork.org/scripts/487244/1326878/gm-import-export.js

  1. // ==UserScript==
  2. // @name gm-import-export
  3. // @description Helper functions for importing and exporting stored values.
  4. // @author Jason Kwok
  5. // @namespace https://jasonhk.dev/
  6. // @version 1.0.0
  7. // @license MIT
  8. // ==/UserScript==
  9.  
  10. function GM_importValues(values, cleanImport = false)
  11. {
  12. if (cleanImport)
  13. {
  14. for (const key of GM_listValues())
  15. {
  16. GM_deleteValue(key);
  17. }
  18. }
  19.  
  20. for (const key of Object.keys(values))
  21. {
  22. GM_setValue(key, values[key]);
  23. }
  24. }
  25.  
  26. function GM_exportValues()
  27. {
  28. const values = {};
  29. for (const key of GM_listValues())
  30. {
  31. values[key] = GM_getValue(key);
  32. }
  33.  
  34. return values;
  35. }
  36.  
  37. GM.importValues = async function importValues(values, cleanImport = false)
  38. {
  39. if (cleanImport)
  40. {
  41. const promises = [];
  42. for (const key of await GM.listValues())
  43. {
  44. promises.push(GM.deleteValue(key));
  45. }
  46.  
  47. await Promise.all(promises);
  48. }
  49.  
  50. const promises = [];
  51. for (const key of Object.keys(values))
  52. {
  53. promises.push(GM.setValue(key, values[key]));
  54. }
  55.  
  56. await Promise.all(promises);
  57. }
  58.  
  59. GM.exportValues = async function exportValues()
  60. {
  61. const keys = await GM.listValues();
  62.  
  63. const promises = [];
  64. for (const key of keys)
  65. {
  66. promises.push(GM.getValue(key));
  67. }
  68.  
  69. const values = await Promise.all(promises);
  70. return Object.fromEntries(keys.map((key, i) => [key, values[i]]));
  71. }