chrome 的js格式化功能提取


網上找到在線或開源的js格式化功能 效果都不是很好
chrome版本為 70.0.3538.110

  1. 搜索 :formatted 發現在 resources.pak
  2. 下載工具解包resources.pak, 搜索發現 V:\70.0.3538.110\resources\unknown\28805
  3. 發現按鈕代碼 _toggleFormatScriptSource
    this._button = new UI.ToolbarButton(Common.UIString('Pretty print'), 'largeicon-pretty-print');
    this._button.addEventListener(UI.ToolbarButton.Events.Click, this._toggleFormatScriptSource, this);
  4. _toggleFormatScriptSource 繼續跟蹤找到
    Sources.sourceFormatter.format
  5. V:\111\28783.js
    _runTask('format', parameters
  6. 原來有下載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
  7. 從github查看chrome的源碼, 最新版沒有, 到2018的分支可以找到部分
    https://github.com/chromium/chromium/tree/d893a023c6a2ad473795fc680170c2a018eedab3/third_party/blink/renderer/devtools/front_end/formatter_worker
  8. 創建一個htm逐個加載需要的js, 發現動態加載一個js文件formatter_worker.js, 從源碼上找到特征搜索, 然后找到28754
  9. 28754 這個文件是格式化核心部分, 其他js都可以刪掉了
  10. 修改部分代碼直接可以用htm調用了, 調用方法
    var js_fmt = FormatterWorker.format('text/javascript', js_code, ' ');
    console.log(js_fmt.content);

如果要兼容其他瀏覽器, 如很老的IE7之類的, 老版本js引擎等, 需要修改很多東西
修改過程

  1. 改名formatter_worker.js
  2. 格式化
  3. let修改為var, class無法使用, 用function代替, 手動修改很多
  4. Runtime對象實際沒用到, 刪除以及相關的
  5. 反引號無法支持, 修改為引號, delete關鍵詞無法使用, =>部分替換為function
  6. var關鍵詞無法使用, class修改以及static函數修改, for of無法使用修改為for in, Set{}無法使用修改為[]
  7. defineProperty無法使用修改為成員,
    Set, Map, Promise, Symbol無法使用修改相關部分代碼,
    self無法使用, 修改相關
    bind無法使用, 添加一個參數傳遞
    loadPlugins修改防止成員進入for
    postMessage無法使用, 修改相關
  8. 最終可以運行了, 但是結果不對, 把const全改成var, 可以了

同樣的辦法適用於opera36
解包工具
https://github.com/myfreeer/chrome-pak-customizer/releases

  1. _toggleFormatScriptSource
  2. _formatUISourceCodeScript
  3. this._workspace.uiSourceCode(this._projectId, uiSourceCodePath)
  4. FormatterWorker =


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM