网上找到在线或开源的js格式化功能 效果都不是很好
chrome版本为 70.0.3538.110
- 搜索 :formatted 发现在 resources.pak
- 下载工具解包resources.pak, 搜索发现 V:\70.0.3538.110\resources\unknown\28805
- 发现按钮代码 _toggleFormatScriptSource
this._button = new UI.ToolbarButton(Common.UIString('Pretty print'), 'largeicon-pretty-print');
this._button.addEventListener(UI.ToolbarButton.Events.Click, this._toggleFormatScriptSource, this); - _toggleFormatScriptSource 继续跟踪找到
Sources.sourceFormatter.format - V:\111\28783.js
_runTask('format', parameters - 原来有下载chrome的源码版本是 39.0, 对不上, 这个版本也有格式化, 但是效果很不好
E:\SVN\Other\chrome\trunk\src\chrome\VERSION
E:\SVN\Other\chrome\trunk\deps\reference_builds\chrome_linux\resources\inspector\script_formatter_worker - 从github查看chrome的源码, 最新版没有, 到2018的分支可以找到部分
https://github.com/chromium/chromium/tree/d893a023c6a2ad473795fc680170c2a018eedab3/third_party/blink/renderer/devtools/front_end/formatter_worker - 创建一个htm逐个加载需要的js, 发现动态加载一个js文件formatter_worker.js, 从源码上找到特征搜索, 然后找到28754
- 28754 这个文件是格式化核心部分, 其他js都可以删掉了
- 修改部分代码直接可以用htm调用了, 调用方法
var js_fmt = FormatterWorker.format('text/javascript', js_code, ' ');
console.log(js_fmt.content);
如果要兼容其他浏览器, 如很老的IE7之类的, 老版本js引擎等, 需要修改很多东西
修改过程
- 改名formatter_worker.js
- 格式化
- let修改为var, class无法使用, 用function代替, 手动修改很多
- Runtime对象实际没用到, 删除以及相关的
- 反引号无法支持, 修改为引号, delete关键词无法使用, =>部分替换为function
- var关键词无法使用, class修改以及static函数修改, for of无法使用修改为for in, Set{}无法使用修改为[]
- defineProperty无法使用修改为成员,
Set, Map, Promise, Symbol无法使用修改相关部分代码,
self无法使用, 修改相关
bind无法使用, 添加一个参数传递
loadPlugins修改防止成员进入for
postMessage无法使用, 修改相关 - 最终可以运行了, 但是结果不对, 把const全改成var, 可以了
同样的办法适用于opera36
解包工具
https://github.com/myfreeer/chrome-pak-customizer/releases
- _toggleFormatScriptSource
- _formatUISourceCodeScript
- this._workspace.uiSourceCode(this._projectId, uiSourceCodePath)
- FormatterWorker =