最近写了一个谷歌浏览器插件(Chrome extension),拿出来分享下,希望能提升大家的工作效率。

一、背景


先说痛点:日常开发中,经常需要不停的把接口输出的JSON拷贝到在线JSON格式化页面进行校验、查看和对比等操作,但是现在主流的在线JSON格式化网站都只支持单个操作,如果想同时查看多条JSON,那么就得开多个浏览器标签页,效率非常底下。比如这样



想看另一条JSON必须切换标签页,重复的操作一两次还可以,久而久之就无法忍受了。如果能把这些JSON都在一个页面上格式化就好了。

二、尝试解决


一个页面格式化多条JSON,那就是从本来的一个操作区域变成多个操作区域。首先想到的是拷贝下别人的代码,初始化对象的时候多初始化几个,这样就一个变多个了。于是找到国内某搜索排名靠前的JSON格式化网站来研究。看看他们的js




看了后非常疑惑,js为什么要写成这样?这个_0x6eb0对象里的元素为什么都转成了16进制的,刚开始还想着挨个转回来看看到底是什么,突然想到Chrome已经拿到了这个对象,打印一下就可以了



到这里才明白了,就是不让你舒服的看源码。不过这个js还好,想拿来用的话恢复和修改的难度不大,看看另一个js



1万多行混淆的代码,变量名都替换成了短的,想看某个变量怎么定义的、方法在哪里调用过,搜索都没办法搜索,基本放弃了。

三、拨云见日

既然国内的JSON格式化网站没法抄了,就到国外找找,Google上搜索JSON Formatter,前几个网站界面都不一样,但是用的都是JSONEditor
<https://github.com/josdejong/jsoneditor>这个编辑器。JSONEditor的简介是:"A web-based tool
to view, edit, format, and validate JSON",看来能满足需求了,看下这个编辑器的效果图



看下对应的代码
<!DOCTYPE html> <html lang="en"> <head> <title>test page</title> <meta
http-equiv="Content-Type" content="text/html;charset=utf-8"> <link rel
="stylesheet" type="text/css" href="dist/jsoneditor.min.css"> <script type
="text/javascript" src="dist/jsoneditor.min.js"></script> <style type="text/css"
> #container { width: 500px; height: 600px; } </style> </head> <body> <div id
="container"></div> <script type="text/javascript"> var container =
document.getElementById('container'); var options = { mode: 'code', onError:
function (err) { alert(err.toString()); } }; var editor = new
JSONEditor(container, options);</script> </body> </html>

非常简洁,这个editor还自带json格式化、压缩和去除转义的功能,无需自己实现。为了方便布局,用下Bootstrap的栅栏模式,看看多个editor在一起的效果



对应的代码是
<!DOCTYPE html> <html lang="en"> <head> <title>test page</title> <meta
http-equiv="Content-Type" content="text/html;charset=utf-8"> <link rel
="stylesheet" type="text/css" href="dist/jsoneditor.min.css"> <link rel
="stylesheet" type="text/css" href="dist/bootstrap.min.css"> <script type
="text/javascript" src="dist/jquery.min.js"></script> <script type
="text/javascript" src="dist/jsoneditor.min.js"></script> <script type
="text/javascript" src="dist/bootstrap.min.js"></script> </head> <body> <div
class="container-fluid"> <div class="row"> <div class="col-xs-12 col-sm-6
col-md-6 col-lg-6"> <div id="container1"></div> </div> <div class="col-xs-12
col-sm-6 col-md-6 col-lg-6"> <div id="container2"></div> </div> </div> </div> <
scripttype="text/javascript"> var container1 = document.getElementById('
container1'); var container2 = document.getElementById('container2'); var
options= { mode: 'code', onError: function (err) { alert(err.toString()); } };
var editor1 = new JSONEditor(container1, options); var editor2 = new
JSONEditor(container2, options);var wHeight = $(window).height(); $("
#container1,#container2").height(wHeight); </script> </body> </html> View Code
到这里又该疑惑了:一个页面到底放几个editor合适。最终决定根据浏览器窗口宽度动态控制个数
function getMaxBoxCount() { var screenWidth = $(window).width(); var
maxBoxCount = 0; if (screenWidth < 1024) { maxBoxCount = 1; } else if
(screenWidth >= 1024 && screenWidth < 1920) {//1080p maxBoxCount = 2; } else if
(screenWidth >= 1920 && screenWidth < 2560) {//2k maxBoxCount = 3; } else if
(screenWidth >= 2560 && screenWidth < 3840) {//4k maxBoxCount = 4; } else if
(screenWidth >= 3840 && screenWidth < 5120) {//5k maxBoxCount = 5; } else if
(screenWidth >= 5120) {//5k+ maxBoxCount = 6; } return maxBoxCount; }
如果用户的显示器是5k的,那么放6个editor,一个页面同时显示6段JSON,基本够用了。如果不够再开一个标签页,就是12个了。

当然也不强制必须开几个,允许关掉editor为剩下的editor获取更大的显示宽度。这里需要注意的就是:单页应用不停的关闭和增加editor对象必须要考虑销毁,否则越来越卡。JSONEditor提供了JSONEditor.destroy()方法,文档里是这样描述destroy方法的:"Destroy
the editor. Clean up DOM, event listeners, and web workers."。

调用destroy方法之前必须得有editor对象,所以初始化的时候就给存起来
var jsonEditorArr = []; var cnr = $("[data-tgt='container']"); $.each(cnr,
function (i, v) { editor = new JSONEditor(v, jsonEditorOptions);
jsonEditorArr.push(editor); });
之后每次删除和增加editor都必须维护这个jsonEditorArr数组
var idx = $(this).parents(".mainBox").next().index(); jsonEditorArr.splice(idx,
0, editor);//增加 jsonEditorArr[idx].destroy(); jsonEditorArr.splice(idx, 1);//移除
至此功能就差不多了,继续为这个插件加一些常用功能

1.复制

复制editor里的JSON到剪切板,再去别的地方粘贴出来结构不乱。使用的是clipboard-polyfill
<https://github.com/lgarron/clipboard-polyfill>
这个库,不需要初始化和销毁对象等操作,直接调用api无脑copy即可,省事省心。示例代码
clipboard.writeText(jsonCopy).then(function () { console.log('ok'); }, function
(err) { console.log(err); });
2.粘贴

别的地方复制的JSON,到这里不需要右键然后粘贴了,直接点粘贴按钮即可,每次操作省一次鼠标右击。同样借助了clipboard-polyfill
<https://github.com/lgarron/clipboard-polyfill>这个库。示例代码
clipboard.readText().then(function (result) { console.log('剪切板里的内容是:'+result);
},function (err) { console.log(err); });
3.下载

保存JSON到本地,省的复制全部,然后到本地新建txt粘贴保存了。使用了FileSaver.js
<https://github.com/eligrey/FileSaver.js>,示例代码
var blob = new Blob([jsonData], { type: "text/plain;charset=utf-8" });
saveAs(blob,"jsonviewer.txt");
至此,功能就都完成了,来看看最终的效果图



四、感谢

Bootstrap <https://github.com/twbs/bootstrap>

ace <https://github.com/ajaxorg/ace>

jsoneditor <https://github.com/josdejong/jsoneditor>

clipboard-polyfill <https://github.com/lgarron/clipboard-polyfill>

FileSaver.js <https://github.com/eligrey/FileSaver.js>

toastr <https://github.com/CodeSeven/toastr>

用到了如上库,感谢无私分享

五、下载与安装

GitHub:https://github.com/oppoic/JSONViewer/
<https://github.com/oppoic/JSONViewer/>

Chrome web store:
https://chrome.google.com/webstore/detail/jsonviewer/khbdpaabobknhhlpglenglkkhdmkfnca

<https://chrome.google.com/webstore/detail/jsonviewer/khbdpaabobknhhlpglenglkkhdmkfnca>

crx文件:https://github.com/oppoic/JSONViewer/raw/master/crx/JSONViewer.crx
<https://github.com/oppoic/JSONViewer/raw/master/crx/JSONViewer.crx>

注:

1)crx文件安装方式:打开Chrome浏览器 - 更多工具 - 扩展程序,把crx文件拖进来

2)GitHub源码安装方式:下载源码,打开Chrome浏览器 - 更多工具 - 扩展程序,打开“开发者模式” - 加载已解压的扩展程序 -
选择源码的src目录 - 确定

六、总结


本插件完全是前端实现,可以双击html页面运行,也可以发布到服务器上。做成谷歌浏览器插件完全是为了方便:每次需要格式化JSON就点谷歌浏览器右上角的插件图标即可。

想要运行HTML页面的到源码包里找这个文件:JSONViewer\test\jsonviewer-test2.html


本文地址:https://www.cnblogs.com/oppoic/p/10444012.html,如果觉得不错,请不吝点个赞并到Github上Star本项目,谢谢!

 

友情链接
ioDraw流程图
API参考文档
OK工具箱
云服务器优惠
阿里云优惠券
腾讯云优惠券
华为云优惠券
站点信息
问题反馈
邮箱:ixiaoyang8@qq.com
QQ群:637538335
关注微信