在本地启用 chrome cdp,从 docker 连接时使用 mitmproxy 解决 | GGAMI.NETChrome 只能通过 localhost、127.0.0.1 访问。
所以以前我会通过下面的 Windows shell 命令来解决:
netsh advfirewall firewall delete rule
name
=
"Allow Port 9222"
netsh interface portproxy delete v4tov4
listenport
=
9222
listenaddress
=
0.0
.0.0
timeout
3
netsh advfirewall firewall
add
rule
name
=
"Allow Port 9222"
dir
=
in
action
=
allow
protocol
=
TCP
localport
=
9222
start /b cmd /c call
"C:\Program Files\Google\Chrome\Application
\c
hrome.exe"
--remote-debugging-port
=
9222
--lang
=
ko-KR --no-default-browser-check --no-first-run --disable-dev-shm-usage --window-size
=
2560,1440
--start-maximized --disable-infobars
timeout
5
netsh interface portproxy
add
v4tov4
listenport
=
9222
listenaddress
=
0.0
.0.0
connectport
=
9222
connectaddress
=
127.0
.0.1
不过这样做有个问题:必须等 Chrome 启动之后,再用 netsh 开放连接。
因此,由于总是在 Chrome 启动之后才进行操作,会产生 5 秒的延迟。
通过运行下面的命令启动 mitmproxy:
mitmproxy --mode reverse:http://127.0.0.1:9222/ --listen-port 9223 -s modify_host.py
这样,在 Docker 容器中运行的进程使用 puppeteer 或 playwright 连接时,
只要将目标地址设置为 host.docker.internal:9223,实际连接后就会在本地启动的浏览器中运行。
C:\Program Files\Google\Chrome\Application\chrome.exe" --remote-debugging-port=9222 --lang=ko-KR --no-default-browser-check --no-first-run --disable-dev-shm-usage --window-size=2560,1440 --start-maximized --disable-infobars
这样做有什么用呢?实际开发或部署到服务器时,应用通常都是在 Docker 中运行的,
但有时很难确认它是否按预期正常工作。
所以,开发时需要快速推进开发,就可以用这种方式;
等到实际在服务器上运行时,再检查它在服务器上是否运行正常即可。
我之前用过类似 puppeteer-screen-recorder 的工具来检查。