Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
seleniumhq
GitHub Repository: seleniumhq/selenium
Path: blob/trunk/javascript/selenium-webdriver/devtools/CDPConnection.js
2884 views
1
// Licensed to the Software Freedom Conservancy (SFC) under one
2
// or more contributor license agreements. See the NOTICE file
3
// distributed with this work for additional information
4
// regarding copyright ownership. The SFC licenses this file
5
// to you under the Apache License, Version 2.0 (the
6
// "License"); you may not use this file except in compliance
7
// with the License. You may obtain a copy of the License at
8
//
9
// http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied. See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
18
const logging = require('../lib/logging')
19
20
const RESPONSE_TIMEOUT = 1000 * 30
21
22
class CDPConnection {
23
constructor(wsConnection) {
24
this._wsConnection = wsConnection
25
this.cmd_id = 0
26
this.targetID = null
27
this.sessionId = null
28
}
29
30
execute(method, params, callback) {
31
let message = {
32
method,
33
id: this.cmd_id++,
34
}
35
if (this.sessionId) {
36
message['sessionId'] = this.sessionId
37
}
38
39
const mergedMessage = Object.assign({ params: params }, message)
40
this._wsConnection.send(JSON.stringify(mergedMessage), callback)
41
}
42
43
async send(method, params) {
44
let cdp_id = this.cmd_id++
45
let message = {
46
method,
47
id: cdp_id,
48
}
49
if (this.sessionId) {
50
message['sessionId'] = this.sessionId
51
}
52
53
const mergedMessage = Object.assign({ params: params }, message)
54
this._wsConnection.send(JSON.stringify(mergedMessage))
55
56
return new Promise((resolve, reject) => {
57
const timeoutId = setTimeout(() => {
58
reject(new Error(`Request with id ${cdp_id} timed out`))
59
handler.off('message', listener)
60
}, RESPONSE_TIMEOUT)
61
62
const listener = (data) => {
63
try {
64
const payload = JSON.parse(data.toString())
65
if (payload.id === cdp_id) {
66
clearTimeout(timeoutId)
67
handler.off('message', listener)
68
resolve(payload)
69
}
70
} catch (err) {
71
logging.getLogger(logging.Type.BROWSER).severe(`Failed parse message: ${err.message}`)
72
}
73
}
74
75
const handler = this._wsConnection.on('message', listener)
76
})
77
}
78
}
79
80
exports.CdpConnection = CDPConnection
81
82