# -*- coding: utf-8 -*-
import sys
sys.stdout.reconfigure(encoding='utf-8')
import websocket, json, time

ws_url = 'ws://localhost:9222/devtools/page/AF7901AD02F8B4871EB42FDB587C2F9A'
ws = websocket.create_connection(ws_url)
ws.settimeout(10)

TITLE = '放春假的孩子开心到"模糊"，而家长还在焦虑"弯道超车"？'

# 先点击标题区域
cmd = json.dumps({'id': 1, 'method': 'Runtime.evaluate', 'params': {
    'expression': '''
    (function() {
        var title = document.getElementById("title");
        if (title) {
            title.focus();
            title.click();
            return "focused and clicked";
        }
        return "not found";
    })()
    '''}})
ws.send(cmd)
time.sleep(0.5)

# 然后填入内容
cmd2 = json.dumps({'id': 2, 'method': 'Runtime.evaluate', 'params': {
    'expression': f'''
    (function() {{
        var title = document.getElementById("title");
        if (title) {{
            title.value = "{TITLE}";
            // 触发多个事件确保被识别
            title.dispatchEvent(new InputEvent('input', {{ bubbles: true, data: "{TITLE}" }}));
            title.dispatchEvent(new Event('change', {{ bubbles: true }}));
            title.dispatchEvent(new Event('blur', {{ bubbles: true }}));
            return "value set to: " + title.value;
        }}
        return "element not found";
    }})()
    '''}})
ws.send(cmd2)
time.sleep(0.5)
result = ws.recv()
data = json.loads(result)
print('设置结果:', data.get('result', {}).get('result', {}).get('value', 'NO_DATA'))

# 验证
cmd3 = json.dumps({'id': 3, 'method': 'Runtime.evaluate', 'params': {
    'expression': 'document.getElementById("title") ? document.getElementById("title").value : "not found"'}})
ws.send(cmd3)
time.sleep(0.3)
result3 = ws.recv()
data3 = json.loads(result3)
print('验证结果:', data3.get('result', {}).get('result', {}).get('value', 'NO_DATA'))

ws.close()
