Path: blob/trunk/javascript/selenium-webdriver/devtools/CDPConnection.js
2884 views
// Licensed to the Software Freedom Conservancy (SFC) under one1// or more contributor license agreements. See the NOTICE file2// distributed with this work for additional information3// regarding copyright ownership. The SFC licenses this file4// to you under the Apache License, Version 2.0 (the5// "License"); you may not use this file except in compliance6// with the License. You may obtain a copy of the License at7//8// http://www.apache.org/licenses/LICENSE-2.09//10// Unless required by applicable law or agreed to in writing,11// software distributed under the License is distributed on an12// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY13// KIND, either express or implied. See the License for the14// specific language governing permissions and limitations15// under the License.1617const logging = require('../lib/logging')1819const RESPONSE_TIMEOUT = 1000 * 302021class CDPConnection {22constructor(wsConnection) {23this._wsConnection = wsConnection24this.cmd_id = 025this.targetID = null26this.sessionId = null27}2829execute(method, params, callback) {30let message = {31method,32id: this.cmd_id++,33}34if (this.sessionId) {35message['sessionId'] = this.sessionId36}3738const mergedMessage = Object.assign({ params: params }, message)39this._wsConnection.send(JSON.stringify(mergedMessage), callback)40}4142async send(method, params) {43let cdp_id = this.cmd_id++44let message = {45method,46id: cdp_id,47}48if (this.sessionId) {49message['sessionId'] = this.sessionId50}5152const mergedMessage = Object.assign({ params: params }, message)53this._wsConnection.send(JSON.stringify(mergedMessage))5455return new Promise((resolve, reject) => {56const timeoutId = setTimeout(() => {57reject(new Error(`Request with id ${cdp_id} timed out`))58handler.off('message', listener)59}, RESPONSE_TIMEOUT)6061const listener = (data) => {62try {63const payload = JSON.parse(data.toString())64if (payload.id === cdp_id) {65clearTimeout(timeoutId)66handler.off('message', listener)67resolve(payload)68}69} catch (err) {70logging.getLogger(logging.Type.BROWSER).severe(`Failed parse message: ${err.message}`)71}72}7374const handler = this._wsConnection.on('message', listener)75})76}77}7879exports.CdpConnection = CDPConnection808182