網上找到在線或開源的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 =