Prettify JSON Selection

Adds a shortcut(Shift + Alt(Option) + F) and context menu option to prettify code selection.

目前为 2024-10-11 提交的版本。查看 最新版本

  1. // ==UserScript==
  2. // @name Prettify JSON Selection
  3. // @namespace vengut.github.io
  4. // @version 2024-10-10
  5. // @description Adds a shortcut(Shift + Alt(Option) + F) and context menu option to prettify code selection.
  6. // @license MIT
  7. // @author Venkat G
  8. // @match *://*/*
  9. // @icon data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 100 100%22><text y=%22.9em%22 font-size=%2290%22>📄</text></svg>
  10. // @grant GM_registerMenuCommand
  11. // ==/UserScript==
  12.  
  13. (function () {
  14. "use strict";
  15.  
  16. GM_registerMenuCommand("Prettify", prettifyJson);
  17.  
  18. document.querySelector("body").addEventListener("keydown", (event) => {
  19. // Shift + Alt(Option) + F
  20. if (event.shiftKey && event.altKey && event.key === "Ï") {
  21. prettifyJson();
  22. }
  23. });
  24.  
  25. function prettifyJson() {
  26. try {
  27. let text = "";
  28.  
  29. // https://stackoverflow.com/a/5379408
  30. if (window.getSelection) {
  31. text = window.getSelection().toString();
  32. } else if (document.selection && document.selection.type != "Control") {
  33. text = document.selection.createRange().text;
  34. }
  35.  
  36. const json = JSON.stringify(JSON.parse(text), null, 2);
  37. const blob = new Blob([json], { type: "application/json" });
  38. const blobUrl = URL.createObjectURL(blob);
  39. window.open(blobUrl);
  40. } catch (err) {}
  41. }
  42. })();