类: Debugger

An alternate transport for Chrome’s remote debugging protocol.

进程:主进程

Chrome Developer Tools 在 JavaScript 运行时提供了一个 special binding , 允许与页面进行交互和检测。

  1. const { BrowserWindow } = require('electron')
  2. const win = new BrowserWindow()
  3. try {
  4. win.webContents.debugger.attach('1.1')
  5. } catch (err) {
  6. console.log('Debugger attach failed : ', err)
  7. }
  8. win.webContents.debugger.on('detach', (event, reason) => {
  9. console.log('Debugger detached due to : ', reason)
  10. })
  11. win.webContents.debugger.on('message', (event, method, params) => {
  12. if (method === 'Network.requestWillBeSent') {
  13. if (params.request.url === 'https://www.github.com') {
  14. win.webContents.debugger.detach()
  15. }
  16. }
  17. })
  18. win.webContents.debugger.sendCommand('Network.enable')

事件

Event: ‘detach’

返回:

  • event Event
  • reason String - 分离调试器的原因

Emitted when the debugging session is terminated. This happens either when webContents is closed or devtools is invoked for the attached webContents.

Event: ‘message’

返回:

  • event Event
  • method String - 方法名.
  • params any - Event parameters defined by the ‘parameters’ attribute in the remote debugging protocol.
  • sessionId String - Unique identifier of attached debugging session, will match the value sent from debugger.sendCommand.

Emitted whenever the debugging target issues an instrumentation event.

实例方法

debugger.attach([protocolVersion])

  • protocolVersion String (optional) - 需要调试的协议的版本

添加调试器到 webContents

debugger.isAttached()

Returns Boolean - 表示调试器是否成功添加到 webContents

debugger.detach()

webContents 里分离调试器.

debugger.sendCommand(method[, commandParams, sessionId])

  • method 字符串 - 方法名称,应该为远程调试协议中定义的方法之一。
  • commandParams any (optional) - JSON object with request parameters.
  • sessionId String (optional) - send command to the target with associated debugging session id. The initial value can be obtained by sending Target.attachToTarget message.

返回 Promise<any> - 一个 promise,远程调试协议中的命令描述的“returns”属性定义的响应,或者显示命令失败的错误消息。

向调试目标发送给定的命令。