Key-Based Config

A script for interfacing with my Key-Based Config UI.

当前为 2021-08-01 提交的版本,查看 最新版本

此脚本不应直接安装。它是供其他脚本使用的外部库,要使用该库请加入元指令 // @require https://update.cn-greasyfork.org/scripts/419978/956314/Key-Based%20Config.js

  1. // ==UserScript==
  2. // @name Key-Based Config
  3. // @author Callum Latham <callumtylerlatham@gmail.com> (https://github.com/ctl2/key-based-config)
  4. // @exclude *
  5. // @description A script for interfacing with my Key-Based Config UI.
  6. // ==/UserScript==
  7.  
  8. let iframeExists = false;
  9.  
  10. function kbcConfigure(storageKey, title, metaTree) {
  11. return new Promise((resolve, reject) => {
  12. if (iframeExists) {
  13. reject(new Error("A key-based-config iFrame already exists."));
  14. } else if (typeof GM.getValue !== "function" || typeof GM.setValue !== "function") {
  15. reject(new Error("The key-based config script requires GM.getValue and GM.setValue permissions."));
  16. } else {
  17. iframeExists = true;
  18. const kbcSrc = "https://callumlatham.com/key-based-config/";
  19.  
  20. // Make iFrame
  21. let iframe = document.createElement("iframe");
  22. iframe.src = kbcSrc;
  23. iframe.style.position = "fixed";
  24. iframe.style.height = "100vh";
  25. iframe.style.width = "100vw";
  26.  
  27. // Listen for iFrame communication
  28. window.addEventListener("message", async (message) => {
  29. switch (message.data.event) {
  30. case "open":
  31. // Pass initilisation data
  32. const valueForest = await GM.getValue(storageKey);
  33. iframe.contentWindow.postMessage({
  34. title: title,
  35. metaTree: metaTree,
  36. valueForest: valueForest === undefined ? [] : valueForest
  37. }, "*");
  38. break;
  39. case "change":
  40. // Update stored value
  41. GM.setValue(storageKey, message.data.valueForest);
  42. break;
  43. case "close":
  44. // Close iFrame
  45. iframeExists = false;
  46. iframe.remove();
  47. // Resolve promise
  48. resolve(message.data.valueForest);
  49. break;
  50. default:
  51. // No need to error the promise here; I'm probably just observing a message from another script
  52. console.warn("Unrecognised message 'event' value observed by key-based config script: '" + message.data.type + "'");
  53. }
  54. });
  55.  
  56. }
  57.  
  58. });
  59.  
  60. }