json-viewer

增加判断,当是访问的json接口地址的时候才初始化json格式化插件到页面

当前为 2020-01-15 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name json-viewer
  3. // @namespace http://tampermonkey.net/
  4. // @version 0.2
  5. // @description 增加判断,当是访问的json接口地址的时候才初始化json格式化插件到页面
  6. // @description 谷歌浏览器直接打开json格式内容的接口地址,可以格式化显示接口返回值,保留key的双引号,支持图片链接预览
  7. // @author sgd
  8. // @match *://*/*
  9. // @grant none
  10. // @require https://code.jquery.com/jquery-3.4.1.min.js
  11. // @icon https://www.easyicon.net/api/resizeApi.php?id=501159&size=128
  12. // ==/UserScript==
  13.  
  14. // jquery.json-viewer 插件 开始
  15. (function($){
  16. /**
  17. * Check if arg is either an array with at least 1 element, or a dict with at least 1 key
  18. * @return boolean
  19. */
  20. function isCollapsable(arg) {
  21. return arg instanceof Object && Object.keys(arg).length > 0;
  22. }
  23.  
  24. /**
  25. * Check if a string represents a valid url
  26. * @return boolean
  27. */
  28. function isUrl(string) {
  29. var regexp = /^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
  30. return regexp.test(string);
  31. }
  32.  
  33. /**
  34. * Transform a json object into html representation
  35. * @return string
  36. */
  37. function json2html(json, options) {
  38. var html = '';
  39. if (typeof json === 'string') {
  40. /* Escape tags */
  41. json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
  42. if (isUrl(json))
  43. html += '<a href="' + json + '" class="json-string">"' + json + '"</a>';
  44. else
  45. html += '<span class="json-string">"' + json + '"</span>';
  46. }
  47. else if (typeof json === 'number') {
  48. html += '<span class="json-literal">' + json + '</span>';
  49. }
  50. else if (typeof json === 'boolean') {
  51. html += '<span class="json-literal">' + json + '</span>';
  52. }
  53. else if (json === null) {
  54. html += '<span class="json-literal">null</span>';
  55. }
  56. else if (json instanceof Array) {
  57. if (json.length > 0) {
  58. html += '[<ol class="json-array">';
  59. for (var i = 0; i < json.length; ++i) {
  60. html += '<li>';
  61. /* Add toggle button if item is collapsable */
  62. if (isCollapsable(json[i])) {
  63. html += '<a href class="json-toggle"></a>';
  64. }
  65. html += json2html(json[i], options);
  66. /* Add comma if item is not last */
  67. if (i < json.length - 1) {
  68. html += ',';
  69. }
  70. html += '</li>';
  71. }
  72. html += '</ol>]';
  73. }
  74. else {
  75. html += '[]';
  76. }
  77. }
  78. else if (typeof json === 'object') {
  79. var key_count = Object.keys(json).length;
  80. if (key_count > 0) {
  81. html += '{<ul class="json-dict">';
  82. for (var key in json) {
  83. if (json.hasOwnProperty(key)) {
  84. html += '<li>';
  85. var keyRepr = options.withQuotes ?
  86. '<span class="json-string">"' + key + '"</span>' : key;
  87. /* Add toggle button if item is collapsable */
  88. if (isCollapsable(json[key])) {
  89. html += '<a href class="json-toggle">' + keyRepr + '</a>';
  90. }
  91. else {
  92. html += keyRepr;
  93. }
  94. html += ': ' + json2html(json[key], options);
  95. /* Add comma if item is not last */
  96. if (--key_count > 0)
  97. html += ',';
  98. html += '</li>';
  99. }
  100. }
  101. html += '</ul>}';
  102. }
  103. else {
  104. html += '{}';
  105. }
  106. }
  107. return html;
  108. }
  109.  
  110. /**
  111. * jQuery plugin method
  112. * @param json: a javascript object
  113. * @param options: an optional options hash
  114. */
  115. $.fn.jsonViewer = function(json, options) {
  116. options = options || {};
  117.  
  118. /* jQuery chaining */
  119. return this.each(function() {
  120.  
  121. /* Transform to HTML */
  122. var html = json2html(json, options);
  123. if (isCollapsable(json))
  124. html = '<a href class="json-toggle"></a>' + html;
  125.  
  126. /* Insert HTML in target DOM element */
  127. $(this).html(html);
  128.  
  129. /* Bind click on toggle buttons */
  130. $(this).off('click');
  131. $(this).on('click', 'a.json-toggle', function() {
  132. var target = $(this).toggleClass('collapsed').siblings('ul.json-dict, ol.json-array');
  133. target.toggle();
  134. if (target.is(':visible')) {
  135. target.siblings('.json-placeholder').remove();
  136. }
  137. else {
  138. var count = target.children('li').length;
  139. var placeholder = count + (count > 1 ? ' items' : ' item');
  140. target.after('<a href class="json-placeholder">' + placeholder + '</a>');
  141. }
  142. return false;
  143. });
  144.  
  145. /* Simulate click on toggle button when placeholder is clicked */
  146. $(this).on('click', 'a.json-placeholder', function() {
  147. $(this).siblings('a.json-toggle').click();
  148. return false;
  149. });
  150.  
  151. if (options.collapsed == true) {
  152. /* Trigger click to collapse all nodes */
  153. $(this).find('a.json-toggle').click();
  154. }
  155. });
  156. };
  157. })(jQuery);
  158. // jquery.json-viewer 插件 结束
  159.  
  160. (function() {
  161. 'use strict';
  162. // 添加样式
  163. var style = document.createElement("style");
  164. style.type = "text/css";
  165. var text = document.createTextNode("body{margin-bottom: 200px;}per{margin:20px;}#btn{position: fixed;top: 20px;right: 20px;background-color: transparent;border: 1px solid rgb(218, 220, 224);border-radius: 4px;box-sizing: border-box;color: rgb(26, 115, 232);cursor: pointer;line-height:30px;}#btn:hover{background-color:rgb(210, 227, 252);} ul.json-dict, ol.json-array {list-style-type: none;margin: 0 0 0 1px;border-left: 1px dotted #ccc;padding-left: 2em;}.json-string {color: #0B7500;}.json-literal {color: #1A01CC;font-weight: bold;}a.json-toggle {position: relative;color: inherit;text-decoration: none;}a.json-toggle:focus {outline: none;}a.json-toggle:before {color: #aaa;content: \"\\25BC\";position: absolute;display: inline-block;width: 1em;left: -1em;}a.json-toggle.collapsed:before {transform: rotate(-90deg);-ms-transform: rotate(-90deg);-webkit-transform: rotate(-90deg);}a.json-placeholder {color: #aaa;padding: 0 1em;text-decoration: none;} a.json-placeholder:hover { text-decoration: underline; }");
  166. style.appendChild(text);
  167. var head = document.getElementsByTagName("head")[0];
  168. head.appendChild(style);
  169.  
  170. var source = $('pre[style="word-wrap: break-word; white-space: pre-wrap;"]');
  171. // 根据上面这一点没办法确定是需要添加json格式化工具,再加上对内容进行判断是不是json格式的内容
  172.  
  173. // 如果是直接打开的json接口地址才需要格式化插件
  174. if(source.length > 0 && isJSON(source.html())){
  175. console.log("json-viewer 插件初始化成功");
  176. source.attr("id", "json-source")
  177. source.hide();
  178. var src = source.html();// 获取到内容
  179. // 添加一个格式化显示的per元素
  180. $("body").append($('<per id="json-renderer"></pre>'))
  181. console.log(src);
  182. // 将内容用eval函数处理下
  183. var input = eval('(' + src + ')');
  184. // 调用格式化方法,参数:是否收缩所有的节点 是否为Key添加双引号
  185. $('#json-renderer').jsonViewer(input, {collapsed: false,withQuotes: true});
  186.  
  187. // 添加原文、格式化后内容的切换按钮
  188. $("body").append('<input type="button" value="View Source" id="btn"/>');
  189. $("body").on("click","#btn",function(){
  190. var v = $(this).val();
  191. if(v=='View Source'){
  192. $(this).val("Format Content");
  193. // 查看原文
  194. $('#json-renderer').hide();
  195. $('#json-source').show();
  196. }else{
  197. $(this).val("View Source");
  198. // 格式化
  199. $('#json-renderer').show();
  200. $('#json-source').hide();
  201. }
  202. });
  203.  
  204. // 所有a标签,看是否是图片,是图片生成预览图
  205. $(document).on("mouseenter mouseleave","a.json-string",function(event){
  206. if(event.type=='mouseenter'){
  207. // 移入
  208. var href = $(this).attr('href');
  209. if(isImg(href)){
  210. $("body").append('<div style="display:none; position: absolute;width:300px;height:200px;" class="preview"><img style="width:100%;height:100%;" src="'+ href +'" /></div>');
  211. var xPos = parseInt(event.pageX) + "px";
  212. var yPos = parseInt(event.pageY) + "px";
  213. $(".preview").css("left", xPos);
  214. $(".preview").css("top", yPos);
  215. $(".preview").show();
  216. }
  217. }else{
  218. // 移除
  219. $(".preview").remove();
  220. }
  221.  
  222. });
  223. }
  224.  
  225. /*检查是否是图片链接*/
  226. function isImg(pathImg) {
  227. var regexp = /^(http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?\/([\w#!:.?+=&%@!\-\/])*\.(gif|jpg|jpeg|png|GIF|JPG|PNG)([\w#!:.?+=&%@!\-\/])?/;
  228. return regexp.test(pathImg);
  229. }
  230. /** 检验内容是否是json格式的内容*/
  231. function isJSON(str) {
  232. if (typeof str == 'string') {
  233. try {
  234. var obj=JSON.parse(str);
  235. if(typeof obj == 'object' && obj ){
  236. return true;
  237. }else{
  238. return false;
  239. }
  240.  
  241. } catch(e) {
  242. console.log('error:'+str+'!!!'+e);
  243. return false;
  244. }
  245. }
  246. console.log('It is not a string!')
  247. }
  248.  
  249.  
  250. })();