Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using remote chrome devtools from Python

I want to use the remote socket debugging stuff for Chrome devtools (link) from Python. I'm using code adapted from here.

I've managed to get ping and list_tabs working. But I can't figure out how to evaluate_javascript. Can anybody tell me what I'm doing wrong?

import subprocess
import time, json, socket

from jca.files import my_paths

def request(tool, destination=None, **kw):
  # Send a command via socket to 'DevToolsService' or 'V8Debugger'
  j = json.dumps(kw)
  request = 'Content-Length:%d\r\nTool:%s\r\n' % (len(j), tool)
  if destination:
    request += 'Destination:%s\r\n' % (destination,)
  request += '\r\n%s\r\n' % (j,)
  sock.send(request)
  if kw.get('command', '') not in RESPONSELESS_COMMANDS:
    time.sleep(.1)
    response = sock.recv(30000)
    if response.strip():
      j = response.split('\r\n\r\n', 1)[1]
      return json.loads(j)

if __name__ == '__main__':
  proc = subprocess.Popen('"%s" --remote-shell-port=9222' % my_paths.chrome_exe)
  RESPONSELESS_COMMANDS = ['evaluate_javascript']
  sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  sock.connect(('localhost', 9222))
  sock.send('ChromeDevToolsHandshake\r\n')
  result = sock.recv(1024)
  print 'ping: ', request('DevToolsService', command='ping')
  time.sleep(4)
  print 'list_tabs: ', request('DevToolsService', command='list_tabs')
  request('V8Debugger', command='evaluate_javascript', 
          data='javascript:window.location.reload()')
  sock.close()
  print 'done'
like image 451
Jesse Aldridge Avatar asked Jul 11 '11 00:07

Jesse Aldridge


2 Answers

I'm sorry for spam, there's a Java library for this: http://code.google.com/p/chromedevtools/

Since you probably chosen Python not at random, you could have it as a reference implementation if running Java code is OK for you. I guess you could check the actual messages sent and received from Java debugger.

like image 68
beefeather Avatar answered Nov 17 '22 23:11

beefeather


The problem was that I didn't set a tab_id for destination. Adding destination=2 to the request call fixes the problem.

like image 39
Jesse Aldridge Avatar answered Nov 18 '22 00:11

Jesse Aldridge