是的,如果您按照说明在 UIWebView 中启用了检查器,则应该可以从 Python 连接到它。我玩弄了它,并弄清楚了如何使用 Web Socket 发送和接收命令。这是使用 websocket-client 的 Python 2.7 脚本
import json
import socket
from websocket import WebSocket
ws = WebSocket()
# if ipv6
ws.io_sock = ws.sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
ws.connect("ws://localhost:9999/devtools/page/1")
counter = 0
def send(method, params):
global counter
counter += 1
# separators is important, you'll get "Message should be in JSON format." otherwise
message = json.dumps({"id": counter, "method": method, "params": params}, separators=(',', ':'))
print "> %s" % (message,)
ws.send(message)
def recv():
result = ws.recv()
print "< %s" % (result,)
send('Runtime.evaluate', {'expression': 'alert("hello from python")'})
recv()
这使用Runtime.evaluate 函数来显示警报。
我尝试针对在模拟器中运行的 MobileSafari 运行它,它运行良好。我注意到两件重要的事情:
- 远程服务器绑定到 IPv6 端口,并且 websocket-client 没有连接覆盖套接字和设置族的线路。不确定在设备上运行还是在 UIWebView 上运行相同。
- 它不喜欢 JSON 中分隔符周围的空格。
使用 gdb 在 MobileSafari 中启用检查器并运行脚本如下所示:
$ ps x | grep MobileSafari
4968 ?? Z 0:00.00 (MobileSafari)
6234 ?? S 0:00.69 /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator5.0.sdk//Applications/MobileSafari.app/MobileSafari
6238 s007 R+ 0:00.00 grep MobileSafari
$ gdb
GNU gdb 6.3.50-20050815 (Apple version gdb-1708) (Thu Nov 3 21:59:02 UTC 2011)
...
(gdb) attach 6234
Attaching to process 6234.
Reading symbols for shared libraries . done
Reading symbols for shared libraries ........................................................................................................................................................ done
0x99798c22 in mach_msg_trap ()
(gdb) p (void *)[WebView _enableRemoteInspector]
$1 = (void *) 0x2ac93ce
(gdb) detach
Detaching from process 6234.
(gdb) quit
$ python debug.py
> {"params":{"expression":"alert(\"hello from python\")"},"id":1,"method":"Runtime.evaluate"}
< {"result":{"result":{"type":"undefined","description":"undefined"}},"id":1}