📅  最后修改于: 2023-12-03 15:13:03.276000             🧑  作者: Mango
WebSocketTransport.js
是Puppeteer库的一部分,它是用JavaScript编写的WebSocket传输协议实现的代码文件。WebSocketTransport是Puppeteer与Chromium浏览器之间使用的一种传输协议。
下面是WebSocketTransport.js中的代码示例:
class WebSocketTransport {
constructor(url) {
this._url = url;
this._lastMessageId = 0;
this._callbacks = new Map();
this._websocket = null;
}
async open() {
return new Promise((resolve, reject) => {
const websocket = new WebSocket(this._url);
websocket.addEventListener('message', (event) =>
this._onmessage(JSON.parse(event.data)));
websocket.addEventListener('error', reject);
websocket.addEventListener('open', () => resolve());
this._websocket = websocket;
});
}
send(message) {
message.id = ++this._lastMessageId;
const msgString = JSON.stringify(message);
this._websocket.send(msgString);
return new Promise((resolve) => {
this._callbacks.set(message.id, resolve);
});
}
_onmessage(message) {
const callback = this._callbacks.get(message.id);
this._callbacks.delete(message.id);
callback(message);
}
close() {
this._websocket.close();
}
}
module.exports = WebSocketTransport;
constructor(url)
:构造函数,接受WebSocket的URL参数。async open()
:使用WebSocket打开连接。send(message)
:发送JSON格式的消息并返回Promise对象。_onmessage(message)
:WebSocket上接收到消息的回调函数。close()
:关闭WebSocket连接。使用Puppeteer库时,可以直接导入WebSocketTransport
类进行使用。
const WebSocketTransport = require('puppeteer/lib/WebSocketTransport');
const transport = new WebSocketTransport('ws://localhost:9222/devtools/browser/b4b06de4-a384-4b89-aa8c-9097380385e5');
await transport.open();
const result = await transport.send({method: 'Network.getAllCookies'});
console.log(result);
transport.close();
WebSocketTransport.js
实现了Puppeteer与Chromium浏览器之间的WebSocket传输协议,这是Puppeteer连接Chromium浏览器的重要组成部分。这个文件代码简洁,易于阅读和使用。