Prettify JSON Selection

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

  1. // ==UserScript==
  2. // @name Prettify JSON Selection
  3. // @namespace vengut.github.io
  4. // @version 2024-10-10
  5. // @description Adds a shortcut(Shift + Ctrl/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. console.log(event.key);
  20. // Shift + Ctrl/Alt/Option + F
  21. if (event.shiftKey && (event.altKey && event.ctrlKey) && (event.key === "Ï" || event.key === "F")) {
  22. prettifyJson();
  23. }
  24. });
  25.  
  26. function prettifyJson() {
  27. try {
  28. let text = "";
  29.  
  30. // https://stackoverflow.com/a/5379408
  31. if (window.getSelection) {
  32. text = window.getSelection().toString();
  33. } else if (document.selection && document.selection.type != "Control") {
  34. text = document.selection.createRange().text;
  35. }
  36.  
  37. const json = JSON.stringify(JSON.parse(text), null, 2);
  38. const blob = new Blob([json], { type: "application/json" });
  39. const blobUrl = URL.createObjectURL(blob);
  40. window.open(blobUrl);
  41. } catch (err) {}
  42. }
  43. })();