是的,如果你已经按照说明在UIWebView中启用了检查器,那么应该可以从Python连接到它。我玩弄了它,并想出了如何使用Web Socket发送和接收命令。下面是使用websocket-client
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函数来显示警报为Python 2.7的脚本。
我试着运行它在模拟器中运行MobileSafari,它运行良好。我注意到两件重要的事情:
- 远程服务器绑定到IPv6端口,并且websocket客户端没有连接没有连接来覆盖套接字并设置系列。不知道它是否会在设备上或UIWebView中运行。
- 它不喜欢JSON中分隔符周围的空格。
这里是什么样子使检查员在MobileSafari用gdb并运行该脚本:
$ 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}
我已经研究过这多一点,这听起来像它应该有可能我做不到找到任何提供良好起点的文档。一旦我找到“连接到这个端口并说出这个协议”,那么我想我可以从那里拿走它。 – Allen 2011-12-23 13:53:07