76 lines
2.1 KiB
Python
Executable File
76 lines
2.1 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""Quick CDP tester: lists targets and evaluates a small script in the first target.
|
|
|
|
Usage:
|
|
python3 scripts/test_cdp.py
|
|
|
|
Requires: requests, websocket-client
|
|
"""
|
|
import requests
|
|
import websocket
|
|
import json
|
|
|
|
|
|
def main():
|
|
try:
|
|
resp = requests.get('http://127.0.0.1:9222/json', timeout=3)
|
|
tabs = resp.json()
|
|
except Exception as e:
|
|
print('ERROR: could not fetch http://127.0.0.1:9222/json ->', e)
|
|
return
|
|
|
|
if not tabs:
|
|
print('No targets returned')
|
|
return
|
|
|
|
print('Found targets:')
|
|
for i, t in enumerate(tabs):
|
|
print(i, t.get('type'), t.get('url'), '-', t.get('title'))
|
|
|
|
target = tabs[0]
|
|
ws_url = target.get('webSocketDebuggerUrl')
|
|
print('\nUsing target[0]:', target.get('url'))
|
|
print('webSocketDebuggerUrl:', ws_url)
|
|
|
|
if not ws_url:
|
|
print('No webSocketDebuggerUrl for target')
|
|
return
|
|
|
|
try:
|
|
# Some Chromium builds require an Origin header to avoid 403 during the websocket handshake
|
|
try:
|
|
ws = websocket.create_connection(ws_url, timeout=5, header=["Origin: http://127.0.0.1"])
|
|
except TypeError:
|
|
# older websocket-client accepts origin kw instead
|
|
ws = websocket.create_connection(ws_url, timeout=5, origin="http://127.0.0.1")
|
|
except Exception as e:
|
|
print('ERROR: could not open websocket to', ws_url, '->', e)
|
|
return
|
|
|
|
idn = 1
|
|
# Enable runtime
|
|
msg = {'id': idn, 'method': 'Runtime.enable'}
|
|
ws.send(json.dumps(msg))
|
|
idn += 1
|
|
try:
|
|
print('Runtime.enable =>', ws.recv())
|
|
except Exception as e:
|
|
print('No response to Runtime.enable:', e)
|
|
|
|
# Evaluate a script that logs and returns a value
|
|
script = "console.log('cdp-test-log'); 12345"
|
|
msg = {'id': idn, 'method': 'Runtime.evaluate', 'params': {'expression': script, 'returnByValue': True}}
|
|
ws.send(json.dumps(msg))
|
|
idn += 1
|
|
try:
|
|
resp = ws.recv()
|
|
print('Runtime.evaluate =>', resp)
|
|
except Exception as e:
|
|
print('No response to Runtime.evaluate:', e)
|
|
|
|
ws.close()
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|