LegacyGM.js

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

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

  1. /* LegacyGM.js
  2. - Version: 1.0.3
  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 function LOAD_LEGACY_GM_SUPPORT() {
  9. if(typeof GM !== 'object') return;
  10.  
  11. const noLegacyInfo = typeof GM_info === 'undefined' && typeof GM?.info !== 'undefined',
  12. onlyModernSet = typeof GM?.setValue === 'function' && typeof GM_setValue === 'undefined',
  13. onlyModernGet = typeof GM?.getValue === 'function' && typeof GM_getValue === 'undefined',
  14. onlyModernList = typeof GM?.listValues === 'function' && typeof GM_listValues === 'undefined',
  15. deleteValueExists = typeof GM?.deleteValue === 'function',
  16. openInTabExists = typeof GM?.openInTab === 'function';
  17.  
  18. if(noLegacyInfo) globalThis.GM_info = GM.info;
  19. if(!onlyModernList && !onlyModernGet && !onlyModernSet) return;
  20.  
  21. const gmCache = {};
  22. const gmFunctions = {
  23. GM_setValue: (key, value) => {
  24. GM.setValue(key, value);
  25. gmCache[key] = value;
  26. },
  27. GM_getValue: (key, defaultValue) => {
  28. return key in gmCache ? gmCache[key] : defaultValue;
  29. },
  30. GM_deleteValue: (key) => {
  31. GM.deleteValue(key);
  32. delete gmCache[key];
  33. },
  34. GM_listValues: () => {
  35. return Object.keys(gmCache);
  36. },
  37. GM_openInTab: (url, options = false) => {
  38. if(openInTabExists)
  39. return GM.openInTab(url, options);
  40.  
  41. return window.open(url, '_blank');
  42. },
  43. };
  44.  
  45. setInterval(async () => {
  46. const keys = await GM.listValues();
  47.  
  48. // Load existing
  49. for(const key of keys) {
  50. gmCache[key] = await GM.getValue(key);
  51. }
  52.  
  53. // Remove old
  54. for(const key in gmCache) {
  55. if(!keys.includes(key)) {
  56. delete gmCache[key];
  57. }
  58. }
  59. }, 1);
  60.  
  61.  
  62. // Define legacy functions
  63. for(const [name, func] of Object.entries(gmFunctions)) {
  64. if(typeof globalThis[name] === 'undefined') {
  65. Object.defineProperty(globalThis, name, {
  66. value: func,
  67. writable: false,
  68. configurable: false,
  69. enumerable: false,
  70. });
  71. }
  72. }
  73. }