背景
puppeteer是一个通过
Devtools
协议来提供操控chrome/chromium浏览器的高阶API的NodeJS库
我负责的一个项目的启动本地开发环境是这样的:使用npm run dev
指令运行webpack-dev-server服务。暴露出访问地址:http://localhost:1314。然后登陆部署到内部项目环境下的应用。获取到账户cookie的entrance
键值对。然后访问本地的开发环境地址,通过document.cookie
语法写入相应的cookie的entrance
键值对。刷新本地开发页面。此时才可正常访问相应的服务端接口。
看到puppeteer库的功能,尝试以上过程通过puppeteer库的自动化功能实现,以达到一键启动本地开发环境的目的。
过程
我的打算是通过puppeteer在当前的chrome浏览器中进行相关的操作。puppeteer.connect(options)
将 Puppeteer 添加到已有的 Chromium 实例。但是options参数中的browser.wsEndpoint
字段表示一个浏览器 websocket 端点链接,该链接是由browser.wsEndpoint()
获取。
正常不能获取到正常运行的浏览器的wsEndpoint
值
How do I access the browser target?
The endpoint is exposed aswebSocketDebuggerUrl
in/json/version
. Note the browser in the URL, rather than page. If Chrome was launched with--remote-debugging-port=0
and chose an open port, the browser endpoint is written to both stderr and the DevToolsActivePort file in browser profile folder.HTTP Endpoints: If started with a remote-debugging-port, these HTTP endpoints are available on the same port.
因此,我决定通过puppeteer.launch
语法开启一个新的浏览器实例,然后在这个新的浏览器上进行自动化操作。相关的启动参数如下:
const browser = puppeteer.launch({
executablePath: 'C:\\chrome.exe',
headless: false, // 关闭无头模式
ignoreHTTPSErrors: false, // 在导航期间忽略 HTTPS 错误
args: ['--start-maximized', '--disable-extensions-expect=D:\\vue-devtools'] // 最大化启动,开启vue-devtools插件
defaultViewport: {
// 为每个页面设置一个默认视口大小
width: 1920,
height: 1080
}
})
后续是将背景节中的描述的操作使用puppeteer
实现出来,代码如下:
// run-browser.js
const main = async () => {
// ... 启动浏览器实例的代码
const page =