#!/usr/bin/env python3
import json, time, urllib.request, websocket
def http_json(path, method="GET"):
    req = urllib.request.Request("http://127.0.0.1:9222" + path, method=method)
    return json.loads(urllib.request.urlopen(req, timeout=10).read().decode())
t = http_json("/json/new?url=about:blank", method="PUT")
ws = websocket.create_connection(t["webSocketDebuggerUrl"], timeout=30)
ws.send(json.dumps({"id": 1, "method": "Runtime.evaluate",
                    "params": {"expression": "1+1", "returnByValue": True}}))
t0 = time.time()
try:
    while time.time() - t0 < 25:
        msg = ws.recv()
        print(f"[{time.time()-t0:.2f}s]", msg[:200])
        if json.loads(msg).get("id") == 1:
            print("EVAL-OK"); break
except Exception as e:
    print("FAIL:", e)
