index.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. /**
  2. * FeHelper Json Format Tools
  3. */
  4. // 一些全局变量
  5. let editor = {};
  6. let LOCAL_KEY_OF_LAYOUT = 'local-layout-key';
  7. let JSON_LINT = 'jsonformat:json-lint-switch';
  8. let EDIT_ON_CLICK = 'jsonformat:edit-on-click';
  9. let AUTO_DECODE = 'jsonformat:auto-decode';
  10. new Vue({
  11. el: '#pageContainer',
  12. data: {
  13. defaultResultTpl: '<div class="x-placeholder"><img src="../json-format/json-demo.jpg" alt="json-placeholder"></div>',
  14. placeHolder: '',
  15. jsonFormattedSource: '',
  16. errorMsg: '',
  17. errorJsonCode: '',
  18. errorPos: '',
  19. jfCallbackName_start: '',
  20. jfCallbackName_end: '',
  21. jsonLintSwitch: true,
  22. autoDecode: false,
  23. fireChange: true,
  24. overrideJson: false
  25. },
  26. mounted: function () {
  27. // 自动开关灯控制
  28. DarkModeMgr.turnLightAuto();
  29. this.placeHolder = this.defaultResultTpl;
  30. this.autoDecode = localStorage.getItem(AUTO_DECODE);
  31. this.autoDecode = this.autoDecode === 'true';
  32. this.jsonLintSwitch = (localStorage.getItem(JSON_LINT) !== 'false');
  33. this.overrideJson = (localStorage.getItem(EDIT_ON_CLICK) === 'true');
  34. this.changeLayout(localStorage.getItem(LOCAL_KEY_OF_LAYOUT));
  35. editor = CodeMirror.fromTextArea(this.$refs.jsonBox, {
  36. mode: "text/javascript",
  37. lineNumbers: true,
  38. matchBrackets: true,
  39. styleActiveLine: true,
  40. lineWrapping: true
  41. });
  42. //输入框聚焦
  43. editor.focus();
  44. // 格式化以后的JSON,点击以后可以重置原内容
  45. window._OnJsonItemClickByFH = (jsonTxt) => {
  46. if (this.overrideJson) {
  47. this.disableEditorChange(jsonTxt);
  48. }
  49. };
  50. editor.on('change', (editor, changes) => {
  51. this.jsonFormattedSource = editor.getValue().replace(/\n/gm, ' ');
  52. this.fireChange && this.format();
  53. });
  54. // 在tab创建或者更新时候,监听事件,看看是否有参数传递过来
  55. if (location.protocol === 'chrome-extension:') {
  56. chrome.tabs.query({currentWindow: true,active: true, }, (tabs) => {
  57. let activeTab = tabs.filter(tab => tab.active)[0];
  58. chrome.runtime.sendMessage({
  59. type: 'fh-dynamic-any-thing',
  60. thing: 'request-page-content',
  61. tabId: activeTab.id
  62. }).then(resp => {
  63. if(!resp || !resp.content) return ;
  64. editor.setValue(resp.content || '');
  65. this.format();
  66. });
  67. });
  68. }
  69. },
  70. methods: {
  71. format: function () {
  72. this.errorMsg = '';
  73. this.placeHolder = this.defaultResultTpl;
  74. this.jfCallbackName_start = '';
  75. this.jfCallbackName_end = '';
  76. let source = editor.getValue().replace(/\n/gm, ' ');
  77. if (!source) {
  78. return false;
  79. }
  80. // JSONP形式下的callback name
  81. let funcName = null;
  82. // json对象
  83. let jsonObj = null;
  84. // 下面校验给定字符串是否为一个合法的json
  85. try {
  86. // 再看看是不是jsonp的格式
  87. let reg = /^([\w\.]+)\(\s*([\s\S]*)\s*\)$/igm;
  88. let matches = reg.exec(source);
  89. if (matches != null) {
  90. funcName = matches[1];
  91. source = matches[2];
  92. }
  93. // 这里可能会throw exception
  94. jsonObj = JSON.parse(source);
  95. } catch (ex) {
  96. // new Function的方式,能自动给key补全双引号,但是不支持bigint,所以是下下策,放在try-catch里搞
  97. try {
  98. jsonObj = new Function("return " + source)();
  99. } catch (exx) {
  100. try {
  101. // 再给你一次机会,是不是下面这种情况: "{\"ret\":\"0\", \"msg\":\"ok\"}"
  102. jsonObj = new Function("return '" + source + "'")();
  103. if (typeof jsonObj === 'string') {
  104. try {
  105. // 确保bigint不会失真
  106. jsonObj = JSON.parse(jsonObj);
  107. } catch (ie) {
  108. // 最后给你一次机会,是个字符串,老夫给你再转一次
  109. jsonObj = new Function("return " + jsonObj)();
  110. }
  111. }
  112. } catch (exxx) {
  113. this.errorMsg = exxx.message;
  114. }
  115. }
  116. }
  117. try{
  118. // 这里多做一个动作,给没有携带双引号的Key都自动加上,防止Long类型失真
  119. const regex = /([{,]\s*)(\w+)(\s*:)/g;
  120. source = source.replace(regex, '$1"$2"$3');
  121. jsonObj = JSON.parse(source);
  122. }catch(e){
  123. // 这里什么动作都不需要做,这种情况下转换失败的,肯定是Value被污染了,抛弃即可
  124. }
  125. // 是json格式,可以进行JSON自动格式化
  126. if (jsonObj != null && typeof jsonObj === "object" && !this.errorMsg.length) {
  127. try {
  128. let sortType = document.querySelectorAll('[name=jsonsort]:checked')[0].value;
  129. if (sortType !== '0') {
  130. jsonObj = JsonABC.sortObj(jsonObj, parseInt(sortType), true);
  131. }
  132. source = JSON.stringify(jsonObj);
  133. } catch (ex) {
  134. // 通过JSON反解不出来的,一定有问题
  135. this.errorMsg = ex.message;
  136. }
  137. if (!this.errorMsg.length) {
  138. if (this.autoDecode) {
  139. (async () => {
  140. let txt = await JsonEnDecode.urlDecodeByFetch(source);
  141. source = JsonEnDecode.uniDecode(txt);
  142. Formatter.format(source);
  143. })();
  144. } else {
  145. Formatter.format(source);
  146. }
  147. this.placeHolder = '';
  148. this.jsonFormattedSource = source;
  149. // 如果是JSONP格式的,需要把方法名也显示出来
  150. if (funcName != null) {
  151. this.jfCallbackName_start = funcName + '(';
  152. this.jfCallbackName_end = ')';
  153. } else {
  154. this.jfCallbackName_start = '';
  155. this.jfCallbackName_end = '';
  156. }
  157. this.$nextTick(() => {
  158. this.updateWrapperHeight();
  159. })
  160. }
  161. }
  162. if (this.errorMsg.length) {
  163. if (this.jsonLintSwitch) {
  164. return this.lintOn();
  165. } else {
  166. this.placeHolder = '<span class="x-error">' + this.errorMsg + '</span>';
  167. return false;
  168. }
  169. }
  170. return true;
  171. },
  172. compress: function () {
  173. if (this.format()) {
  174. let jsonTxt = this.jfCallbackName_start + this.jsonFormattedSource + this.jfCallbackName_end;
  175. this.disableEditorChange(jsonTxt);
  176. }
  177. },
  178. autoDecodeFn: function () {
  179. this.$nextTick(() => {
  180. localStorage.setItem(AUTO_DECODE, this.autoDecode);
  181. this.format();
  182. });
  183. },
  184. uniEncode: function () {
  185. editor.setValue(JsonEnDecode.uniEncode(editor.getValue()));
  186. },
  187. uniDecode: function () {
  188. editor.setValue(JsonEnDecode.uniDecode(editor.getValue()));
  189. },
  190. urlDecode: function () {
  191. JsonEnDecode.urlDecodeByFetch(editor.getValue()).then(text => editor.setValue(text));
  192. },
  193. updateWrapperHeight: function () {
  194. let curLayout = localStorage.getItem(LOCAL_KEY_OF_LAYOUT);
  195. let elPc = document.querySelector('#pageContainer');
  196. if (curLayout === 'up-down') {
  197. elPc.style.height = 'auto';
  198. } else {
  199. elPc.style.height = Math.max(elPc.scrollHeight, document.body.scrollHeight) + 'px';
  200. }
  201. },
  202. changeLayout: function (type) {
  203. let elPc = document.querySelector('#pageContainer');
  204. if (type === 'up-down') {
  205. elPc.classList.remove('layout-left-right');
  206. elPc.classList.add('layout-up-down');
  207. this.$refs.btnLeftRight.classList.remove('selected');
  208. this.$refs.btnUpDown.classList.add('selected');
  209. } else {
  210. elPc.classList.remove('layout-up-down');
  211. elPc.classList.add('layout-left-right');
  212. this.$refs.btnLeftRight.classList.add('selected');
  213. this.$refs.btnUpDown.classList.remove('selected');
  214. }
  215. localStorage.setItem(LOCAL_KEY_OF_LAYOUT, type);
  216. this.updateWrapperHeight();
  217. },
  218. setCache: function () {
  219. this.$nextTick(() => {
  220. localStorage.setItem(EDIT_ON_CLICK, this.overrideJson);
  221. });
  222. },
  223. lintOn: function () {
  224. this.$nextTick(() => {
  225. localStorage.setItem(JSON_LINT, this.jsonLintSwitch);
  226. });
  227. if (!editor.getValue().trim()) {
  228. return true;
  229. }
  230. this.$nextTick(() => {
  231. if (!this.jsonLintSwitch) {
  232. return;
  233. }
  234. let lintResult = JsonLint.lintDetect(editor.getValue());
  235. if (!isNaN(lintResult.line)) {
  236. this.placeHolder = '<div id="errorTips">' +
  237. '<div id="tipsBox">错误位置:' + (lintResult.line + 1) + '行,' + (lintResult.col + 1) + '列;缺少字符或字符不正确</div>' +
  238. '<div id="errorCode">' + lintResult.dom + '</div></div>';
  239. }
  240. });
  241. return false;
  242. },
  243. disableEditorChange: function (jsonTxt) {
  244. this.fireChange = false;
  245. this.$nextTick(() => {
  246. editor.setValue(jsonTxt);
  247. this.$nextTick(() => {
  248. this.fireChange = true;
  249. })
  250. })
  251. },
  252. openOptionsPage: function(){
  253. chrome.runtime.openOptionsPage();
  254. },
  255. setDemo: function () {
  256. let demo = '{"BigIntSupported":995815895020119788889,"date":"20180322","message":"Success !","status":200,"city":"北京","count":632,"data":{"shidu":"34%","pm25":73,"pm10":91,"quality":"良","wendu":"5","ganmao":"极少数敏感人群应减少户外活动","yesterday":{"date":"21日星期三","sunrise":"06:19","high":"高温 11.0℃","low":"低温 1.0℃","sunset":"18:26","aqi":85,"fx":"南风","fl":"<3级","type":"多云","notice":"阴晴之间,谨防紫外线侵扰"},"forecast":[{"date":"22日星期四","sunrise":"06:17","high":"高温 17.0℃","low":"低温 1.0℃","sunset":"18:27","aqi":98,"fx":"西南风","fl":"<3级","type":"晴","notice":"愿你拥有比阳光明媚的心情"},{"date":"23日星期五","sunrise":"06:16","high":"高温 18.0℃","low":"低温 5.0℃","sunset":"18:28","aqi":118,"fx":"无持续风向","fl":"<3级","type":"多云","notice":"阴晴之间,谨防紫外线侵扰"},{"date":"24日星期六","sunrise":"06:14","high":"高温 21.0℃","low":"低温 7.0℃","sunset":"18:29","aqi":52,"fx":"西南风","fl":"<3级","type":"晴","notice":"愿你拥有比阳光明媚的心情"},{"date":"25日星期日","sunrise":"06:13","high":"高温 22.0℃","low":"低温 7.0℃","sunset":"18:30","aqi":71,"fx":"西南风","fl":"<3级","type":"晴","notice":"愿你拥有比阳光明媚的心情"},{"date":"26日星期一","sunrise":"06:11","high":"高温 21.0℃","low":"低温 8.0℃","sunset":"18:31","aqi":97,"fx":"西南风","fl":"<3级","type":"多云","notice":"阴晴之间,谨防紫外线侵扰"}]}}';
  257. editor.setValue(demo);
  258. this.$nextTick(() => {
  259. this.format();
  260. })
  261. }
  262. }
  263. });