如何录制 Electron `webContents` 会话的 `.har`?

How can you record a `.har` of an Electron `webContents` session?

我有一个 Javascript 应用程序生成 Electron 并在其中做很多事情。

我正在尝试调试我遇到的一个奇怪的网络问题,为此,我想使用 HAR 文件来存储 Electron 发出的所有 HTTP 请求的日志。

这可能吗?

是的,可以使用 chrome-har-capturer 完成 - 您可以从 webContents.debugger 传递一堆事件,然后 chrome-har-capturer 会为您将它们转换为 HAR。

示例代码:

const chromeHarCapturer = require('chrome-har-capturer')

let log = []
const webContents = browserWindow.webContents

webContents.debugger.on("message", function(event, method, params) {
  // https://github.com/cyrus-and/chrome-har-capturer#fromlogurl-log-options
  if (!["Page.domContentEventFired", "Page.loadEventFired", "Network.requestWillBeSent", "Network.dataReceived", 
        "Network.responseReceived", "Network.resourceChangedPriority", "Network.loadingFinished", 
        "Network.loadingFailed"].includes(method)) {
    // not relevant to us
    return
  }
  log.push({method, params})

  if (method === 'Network.responseReceived') { // the chrome events don't include the body, attach it manually if we want it in the HAR
    webContents.debugger.sendCommand('Network.getResponseBody', {
      requestId: params.requestId
    }, function(err, result) {
      result.requestId = params.requestId
      log.push({
        method: 'Network.getResponseBody',
        params: result
      })
    })
  }
})

webContents.debugger.once("detach", function() {
  // on detach, write out the HAR
  return chromeHarCapturer.fromLog("http://dummy-url-for-whole-session", log).then(function(har) {
    const path = `/tmp/${Number(new Date())}-har.json`

    fs.writeJson(path, log)

    log = []
  })
})

// subscribe to the required events
webContents.debugger.attach()
webContents.debugger.sendCommand('Network.enable')
webContents.debugger.sendCommand('Page.enable')