浏览器cdp协议-通过在命令中指定 sessionId 属性,实现对会话的“平面”访问
1.指定端口启动浏览器,如"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe" --remote-debugging-port=9333,可以自己设置一下,这样打开的浏览器才可以连接成功,端口设置为了--9333---
2.获取浏览器主程序的ws网址 如:http://localhost:9333/json/version ------》
"webSocketDebuggerUrl": "ws://localhost:9333/devtools/browser/2ef636d7-05f1-48c8-a786-f4c2c16cd9b1"
{
"Browser": "Edg/144.0.3719.82",
"Protocol-Version": "1.3",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/144.0.0.0 Safari/537.36 Edg/144.0.0.0",
"V8-Version": "14.4.24.5",
"WebKit-Version": "537.36 (@f6f6e1fcd9e657331ac288db133ef45210223f60)",
"webSocketDebuggerUrl": "ws://localhost:9333/devtools/browser/2ef636d7-05f1-48c8-a786-f4c2c16cd9b1"
}
3.通过ws客户端连接浏览器服务端=》ws://localhost:9333/devtools/browser/2ef636d7-05f1-48c8-a786-f4c2c16cd9b1
3-0.Target.getTargets(获取所有打开tab页的信息)
发送
{"method":"Target.getTargets","params":{},"id":0}
响应
{
"id": 0,
"result": {
"targetInfos": [
{
"targetId": "6A92DA59D5C2A9B721980CD537C9534E",
"type": "page",
"title": "localhost:9333/json",
"url": "http://localhost:9333/json",
"attached": true,
"canAccessOpener": false,
"browserContextId": "FC106A61CD010E95EF4128F42426C6CF",
"pid": 6240
},
{
"targetId": "F2C6D04B7B286F7DA615F9E8F5374045",
"type": "page",
"title": "讨论区 - Quicker",
"url": "https://getquicker.net/QA",
"attached": false,
"canAccessOpener": false,
"browserContextId": "FC106A61CD010E95EF4128F42426C6CF",
"pid": 0
},
{
"targetId": "7DF5DE193A0AD8267B02B18A9E563F22",
"type": "page",
"title": "about:blank",
"url": "about:blank",
"attached": false,
"canAccessOpener": false,
"browserContextId": "FC106A61CD010E95EF4128F42426C6CF",
"pid": 0
}
]
}
}
3-1.Target.createTarget(新建tab页)
发送
{"method":"Target.createTarget","params":{"url":"https://club.excelhome.net/"},"id":1}
响应
{"id":1,"result":{"targetId":"9BDC8F61844639A491E8871E909A0E95"}}
3-2.Target.attachToTarget(获取tab页的sessionId,为之后与该tab页通信准备)
发送
{"method":"Target.attachToTarget","params":{"targetId":"9BDC8F61844639A491E8871E909A0E95","flatten":true}, "id":2}
响应
{"id":2,"result":{"sessionId":"12978906B8F50BD3879119A21FB48D80"}}
3-3.Runtime.evaluate(向tab页通信-运行js)
发送
{"method":"Runtime.evaluate","params":{"expression":"console.log(1111);1+2+3"}, "sessionId":"12978906B8F50BD3879119A21FB48D80", "id":3}
响应
{"id":3,"result":{"result":{"type":"number","value":6,"description":"6"}},"sessionId":"12978906B8F50BD3879119A21FB48D80"}