Path: blob/trunk/javascript/selenium-webdriver/lib/network.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 { Network: getNetwork } = require('../bidi/network')18const { InterceptPhase } = require('../bidi/interceptPhase')19const { AddInterceptParameters } = require('../bidi/addInterceptParameters')2021class Network {22#callbackId = 023#driver24#network25#authHandlers = new Map()2627constructor(driver) {28this.#driver = driver29}3031// This should be done in the constructor.32// But since it needs to call async methods we cannot do that in the constructor.33// We can have a separate async method that initialises the Network instance.34// However, that pattern does not allow chaining the methods as we would like the user to use it.35// Since it involves awaiting to get the instance and then another await to call the method.36// Using this allows the user to do this "await driver.network.addAuthenticationHandler(callback)"37async #init() {38if (this.#network !== undefined) {39return40}41this.#network = await getNetwork(this.#driver)4243await this.#network.addIntercept(new AddInterceptParameters(InterceptPhase.AUTH_REQUIRED))4445await this.#network.authRequired(async (event) => {46const requestId = event.request.request47const uri = event.request.url48const credentials = this.getAuthCredentials(uri)49if (credentials !== null) {50await this.#network.continueWithAuth(requestId, credentials.username, credentials.password)51return52}5354await this.#network.continueWithAuthNoCredentials(requestId)55})56}5758getAuthCredentials(uri) {59for (let [, value] of this.#authHandlers) {60if (uri.match(value.uri)) {61return value62}63}64return null65}66async addAuthenticationHandler(username, password, uri = '//') {67await this.#init()6869const id = this.#callbackId++7071this.#authHandlers.set(id, { username, password, uri })72return id73}7475async removeAuthenticationHandler(id) {76await this.#init()7778if (this.#authHandlers.has(id)) {79this.#authHandlers.delete(id)80} else {81throw Error(`Callback with id ${id} not found`)82}83}8485async clearAuthenticationHandlers() {86this.#authHandlers.clear()87}88}8990module.exports = Network919293