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

HOST = "localhost"
PORT = 9222

def get_targets():
    url = f'http://{HOST}:{PORT}/json'
    with urllib.request.urlopen(url) as r:
        return json.loads(r.read().decode())

page = None
for t in get_targets():
    if 'appmsg' in t.get('url', '') and 'action=edit' in t.get('url', ''):
        page = t
        break

import websocket
ws = websocket.create_connection(page['webSocketDebuggerUrl'])
ws.settimeout(30)

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

# 方法: 使用Object.getOwnPropertyDescriptor来设置值
print('[Step 1] 尝试设置标题...')
ws.send(json.dumps({
    'id': 1,
    'method': 'Runtime.evaluate',
    'params': {
        'expression': f'''
        (function() {{
            var el = document.getElementById("title");
            if (!el) return "not found";
            
            // 直接设置value属性
            el.setAttribute("value", "{TITLE}");
            
            // 同时设置property
            var nativeInputValueSetter = Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype, "value").set;
            nativeInputValueSetter.call(el, "{TITLE}");
            
            // 触发事件
            el.dispatchEvent(new Event("input", {{ bubbles: true }}));
            el.dispatchEvent(new Event("change", {{ bubbles: true }}));
            
            return "value: " + el.value + ", attr: " + el.getAttribute("value");
        }})()
        '''
    }
}))

time.sleep(0.5)
response = ws.recv()
print('设置结果:', response[:300])

# 验证
print('[Step 2] 验证...')
ws.send(json.dumps({
    'id': 2,
    'method': 'Runtime.evaluate',
    'params': {
        'expression': 'document.getElementById("title").value'
    }
}))

time.sleep(0.3)
response2 = ws.recv()
result = json.loads(response2)
value = result.get('result', {}).get('result', {}).get('value', '')
print('当前值:', value[:50] if value else 'EMPTY')

ws.close()
