LegacyGM.js

A userscript library for adding support back to GM_ non async functions

目前为 2025-05-01 提交的版本,查看 最新版本

此脚本不应直接安装,它是供其他脚本使用的外部库。如果你需要使用该库,请在脚本元属性加入:// @require https://update.cn-greasyfork.org/scripts/534637/1581323/LegacyGMjs.js

  1. /* LegacyGM.js
  2. - Version: 1.0.0
  3. - Author: Haka
  4. - Description: A userscript library for adding support back to GM_ non async functions
  5. - GitHub: https://github.com/Psyyke/A.C.A.S/
  6. */
  7.  
  8. (async () => {
  9. const noLegacyInfo = typeof globalThis?.GM_info === 'undefined' && typeof GM?.info !== 'undefined',
  10. setValueExists = typeof GM?.setValue === 'function',
  11. getValueExists = typeof GM?.getValue === 'function',
  12. deleteValueExists = typeof GM?.deleteValue === 'function',
  13. listValuesExists = typeof GM?.listValues === 'function',
  14. openInTabExists = typeof GM?.openInTab === 'function';
  15.  
  16. if(noLegacyInfo) globalThis.GM_info = GM.info;
  17. if(!listValuesExists && !getValueExists && !setValueExists) return;
  18.  
  19. const gmCache = {};
  20. const gmFunctions = {
  21. GM_setValue: (key, value) => {
  22. GM.setValue(key, value);
  23. gmCache[key] = value;
  24. },
  25. GM_getValue: (key, defaultValue) => {
  26. return key in gmCache ? gmCache[key] : defaultValue;
  27. },
  28. GM_deleteValue: (key) => {
  29. GM.deleteValue(key);
  30. delete gmCache[key];
  31. },
  32. GM_listValues: () => {
  33. return Object.keys(gmCache);
  34. },
  35. GM_openInTab: (url, options = false) => {
  36. if(openInTabExists)
  37. return GM.openInTab(url, options);
  38.  
  39. return window.open(url, '_blank');
  40. },
  41. };
  42.  
  43. setInterval(async () => {
  44. const keys = await GM.listValues();
  45.  
  46. // Load existing
  47. for(const key of keys) {
  48. gmCache[key] = await GM.getValue(key);
  49. }
  50.  
  51. // Remove old
  52. for(const key in gmCache) {
  53. if(!keys.includes(key)) {
  54. delete gmCache[key];
  55. }
  56. }
  57. }, 1);
  58.  
  59.  
  60. // Define legacy functions
  61. for(const [name, func] of Object.entries(gmFunctions)) {
  62. if(typeof globalThis[name] === 'undefined') {
  63. Object.defineProperty(globalThis, name, {
  64. value: func,
  65. writable: false,
  66. configurable: false,
  67. enumerable: false,
  68. });
  69. }
  70. }
  71. });