UNPKG

1.77 kBJavaScriptView Raw
1/**
2 * Copyright 2018 Google Inc. All rights reserved.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16const WebSocket = require('ws');
17
18/**
19 * @implements {!Puppeteer.ConnectionTransport}
20 */
21class WebSocketTransport {
22 /**
23 * @param {string} url
24 * @return {!Promise<!WebSocketTransport>}
25 */
26 static create(url) {
27 return new Promise((resolve, reject) => {
28 const ws = new WebSocket(url, [], { perMessageDeflate: false });
29 ws.addEventListener('open', () => resolve(new WebSocketTransport(ws)));
30 ws.addEventListener('error', reject);
31 });
32 }
33
34 /**
35 * @param {!WebSocket} ws
36 */
37 constructor(ws) {
38 this._ws = ws;
39 this._ws.addEventListener('message', event => {
40 if (this.onmessage)
41 this.onmessage.call(null, event.data);
42 });
43 this._ws.addEventListener('close', event => {
44 if (this.onclose)
45 this.onclose.call(null);
46 });
47 // Silently ignore all errors - we don't know what to do with them.
48 this._ws.addEventListener('error', () => {});
49 this.onmessage = null;
50 this.onclose = null;
51 }
52
53 /**
54 * @param {string} message
55 */
56 send(message) {
57 this._ws.send(message);
58 }
59
60 close() {
61 this._ws.close();
62 }
63}
64
65module.exports = WebSocketTransport;