JSON formatter

Format JSON data in a beautiful way.

当前为 2024-10-10 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name JSON formatter
  3. // @namespace https://gera2ld.space
  4. // @author Gerald <gera2ld@live.com>
  5. // @icon http://cn.gravatar.com/avatar/a0ad718d86d21262ccd6ff271ece08a3?s=80
  6. // @description Format JSON data in a beautiful way.
  7. // @description:zh-CN 更加漂亮地显示JSON数据。
  8. // @version 2.0.11
  9. // @require https://cdn.jsdelivr.net/npm/@violentmonkey/dom@2
  10. // @match *://*/*
  11. // @match file:///*
  12. // @grant GM_addElement
  13. // @grant GM_registerMenuCommand
  14. // ==/UserScript==
  15.  
  16. (function () {
  17. 'use strict';
  18.  
  19. let iframe;
  20. if (testRules([
  21. // text/javascript - file:///foo/bar.js
  22. /^(?:text|application)\/(?:.*?\+)?(?:plain|json|javascript)$/], document.contentType)) formatJSON();
  23. GM_registerMenuCommand('Format JSON', formatJSON);
  24. function testRules(rules, contentType) {
  25. for (const rule of rules) {
  26. if (typeof rule === 'string') {
  27. if (rule === contentType) return true;
  28. } else if (typeof (rule == null ? void 0 : rule.test) === 'function') {
  29. if (rule.test(contentType)) return true;
  30. }
  31. }
  32. return false;
  33. }
  34. function formatJSON() {
  35. if (iframe) return;
  36. const content = JSON.parse(document.body.textContent);
  37. document.body.innerHTML = '';
  38. iframe = GM_addElement(document.body, 'iframe', {
  39. sandbox: 'allow-scripts allow-same-origin',
  40. src: 'https://json.gera2ld.space/embed',
  41. style: `position:fixed;width:100vw;height:100vh;inset:0;border:none`
  42. });
  43. const setData = () => {
  44. iframe.contentWindow.postMessage({
  45. type: 'setData',
  46. payload: content
  47. }, '*');
  48. };
  49. iframe.addEventListener('load', () => {
  50. setData();
  51. });
  52. window.addEventListener('message', e => {
  53. const {
  54. type
  55. } = e.data;
  56. switch (type) {
  57. case 'ready':
  58. {
  59. setData();
  60. break;
  61. }
  62. }
  63. });
  64. }
  65.  
  66. })();