Path: blob/trunk/rb/lib/selenium/webdriver/remote/bridge.rb
1865 views
# frozen_string_literal: true12# Licensed to the Software Freedom Conservancy (SFC) under one3# or more contributor license agreements. See the NOTICE file4# distributed with this work for additional information5# regarding copyright ownership. The SFC licenses this file6# to you under the Apache License, Version 2.0 (the7# "License"); you may not use this file except in compliance8# with the License. You may obtain a copy of the License at9#10# http://www.apache.org/licenses/LICENSE-2.011#12# Unless required by applicable law or agreed to in writing,13# software distributed under the License is distributed on an14# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY15# KIND, either express or implied. See the License for the16# specific language governing permissions and limitations17# under the License.1819module Selenium20module WebDriver21module Remote22class Bridge23autoload :COMMANDS, 'selenium/webdriver/remote/bridge/commands'24autoload :LocatorConverter, 'selenium/webdriver/remote/bridge/locator_converter'2526include Atoms2728PORT = 44442930attr_accessor :http, :file_detector31attr_reader :capabilities3233class << self34attr_reader :extra_commands35attr_writer :element_class, :locator_converter3637def add_command(name, verb, url, &block)38@extra_commands ||= {}39@extra_commands[name] = [verb, url]40define_method(name, &block)41end4243def locator_converter44@locator_converter ||= LocatorConverter.new45end4647def element_class48@element_class ||= Element49end50end5152#53# Initializes the bridge with the given server URL54# @param [String, URI] url url for the remote server55# @param [Object] http_client an HTTP client instance that implements the same protocol as Http::Default56# @api private57#5859def initialize(url:, http_client: nil)60uri = url.is_a?(URI) ? url : URI.parse(url)61uri.path += '/' unless uri.path.end_with?('/')6263@http = http_client || Http::Default.new64@http.server_url = uri65@file_detector = nil6667@locator_converter = self.class.locator_converter68end6970#71# Creates session.72#7374def create_session(capabilities)75response = execute(:new_session, {}, prepare_capabilities_payload(capabilities))7677@session_id = response['sessionId']78capabilities = response['capabilities']7980raise Error::WebDriverError, 'no sessionId in returned payload' unless @session_id8182@capabilities = Capabilities.json_create(capabilities)8384case @capabilities[:browser_name]85when 'chrome', 'chrome-headless-shell'86extend(WebDriver::Chrome::Features)87when 'firefox'88extend(WebDriver::Firefox::Features)89when 'msedge', 'MicrosoftEdge'90extend(WebDriver::Edge::Features)91when 'Safari', 'Safari Technology Preview'92extend(WebDriver::Safari::Features)93when 'internet explorer'94extend(WebDriver::IE::Features)95end96end9798#99# Returns the current session ID.100#101102def session_id103@session_id || raise(Error::WebDriverError, 'no current session exists')104end105106def browser107@browser ||= begin108name = @capabilities.browser_name109name ? name.tr(' -', '_').downcase.to_sym : 'unknown'110end111end112113def status114execute :status115end116117def get(url)118execute :get, {}, {url: url}119end120121#122# timeouts123#124125def timeouts126execute :get_timeouts, {}127end128129def timeouts=(timeouts)130execute :set_timeout, {}, timeouts131end132133#134# alerts135#136137def accept_alert138execute :accept_alert139end140141def dismiss_alert142execute :dismiss_alert143end144145def alert=(keys)146execute :send_alert_text, {}, {value: keys.chars, text: keys}147end148149def alert_text150execute :get_alert_text151end152153#154# navigation155#156157def go_back158execute :back159end160161def go_forward162execute :forward163end164165def url166execute :get_current_url167end168169def title170execute :get_title171end172173def page_source174execute :get_page_source175end176177#178# Create a new top-level browsing context179# https://w3c.github.io/webdriver/#new-window180# @param type [String] Supports two values: 'tab' and 'window'.181# Use 'tab' if you'd like the new window to share an OS-level window182# with the current browsing context.183# Use 'window' otherwise184# @return [Hash] Containing 'handle' with the value of the window handle185# and 'type' with the value of the created window type186#187def new_window(type)188execute :new_window, {}, {type: type}189end190191def switch_to_window(name)192execute :switch_to_window, {}, {handle: name}193end194195def switch_to_frame(id)196id = find_element_by('id', id) if id.is_a? String197execute :switch_to_frame, {}, {id: id}198end199200def switch_to_parent_frame201execute :switch_to_parent_frame202end203204def switch_to_default_content205switch_to_frame nil206end207208QUIT_ERRORS = [IOError].freeze209210def quit211execute :delete_session212http.close213rescue *QUIT_ERRORS214nil215end216217def close218execute :close_window219end220221def refresh222execute :refresh223end224225#226# window handling227#228229def window_handles230execute :get_window_handles231end232233def window_handle234execute :get_window_handle235end236237def resize_window(width, height, handle = :current)238raise Error::WebDriverError, 'Switch to desired window before changing its size' unless handle == :current239240set_window_rect(width: width, height: height)241end242243def window_size(handle = :current)244unless handle == :current245raise Error::UnsupportedOperationError,246'Switch to desired window before getting its size'247end248249data = execute :get_window_rect250Dimension.new data['width'], data['height']251end252253def minimize_window254execute :minimize_window255end256257def maximize_window(handle = :current)258unless handle == :current259raise Error::UnsupportedOperationError,260'Switch to desired window before changing its size'261end262263execute :maximize_window264end265266def full_screen_window267execute :fullscreen_window268end269270def reposition_window(x, y)271set_window_rect(x: x, y: y)272end273274def window_position275data = execute :get_window_rect276Point.new data['x'], data['y']277end278279def set_window_rect(x: nil, y: nil, width: nil, height: nil)280params = {x: x, y: y, width: width, height: height}281params.update(params) { |_k, v| Integer(v) unless v.nil? }282execute :set_window_rect, {}, params283end284285def window_rect286data = execute :get_window_rect287Rectangle.new data['x'], data['y'], data['width'], data['height']288end289290def screenshot291execute :take_screenshot292end293294def element_screenshot(element)295execute :take_element_screenshot, id: element296end297298#299# javascript execution300#301302def execute_script(script, *args)303result = execute :execute_script, {}, {script: script, args: args}304unwrap_script_result result305end306307def execute_async_script(script, *args)308result = execute :execute_async_script, {}, {script: script, args: args}309unwrap_script_result result310end311312#313# cookies314#315316def manage317@manage ||= WebDriver::Manager.new(self)318end319320def add_cookie(cookie)321execute :add_cookie, {}, {cookie: cookie}322end323324def delete_cookie(name)325raise ArgumentError, 'Cookie name cannot be null or empty' if name.nil? || name.to_s.strip.empty?326327execute :delete_cookie, name: name328end329330def cookie(name)331execute :get_cookie, name: name332end333334def cookies335execute :get_all_cookies336end337338def delete_all_cookies339execute :delete_all_cookies340end341342#343# actions344#345346def action(async: false, devices: [], duration: 250)347ActionBuilder.new self, async: async, devices: devices, duration: duration348end349alias actions action350351def send_actions(data)352execute :actions, {}, {actions: data}353end354355def release_actions356execute :release_actions357end358359def print_page(options = {})360execute :print_page, {}, {options: options}361end362363def click_element(element)364execute :element_click, id: element365end366367def send_keys_to_element(element, keys)368keys = upload_if_necessary(keys) if @file_detector369text = keys.join370execute :element_send_keys, {id: element}, {value: text.chars, text: text}371end372373def clear_element(element)374execute :element_clear, id: element375end376377def submit_element(element)378script = "/* submitForm */ var form = arguments[0];\n" \379"while (form.nodeName != \"FORM\" && form.parentNode) {\n " \380"form = form.parentNode;\n" \381"}\n" \382"if (!form) { throw Error('Unable to find containing form element'); }\n" \383"if (!form.ownerDocument) { throw Error('Unable to find owning document'); }\n" \384"var e = form.ownerDocument.createEvent('Event');\n" \385"e.initEvent('submit', true, true);\n" \386"if (form.dispatchEvent(e)) { HTMLFormElement.prototype.submit.call(form) }\n"387388execute_script(script, Bridge.element_class::ELEMENT_KEY => element)389rescue Error::JavascriptError390raise Error::UnsupportedOperationError, 'To submit an element, it must be nested inside a form element'391end392393#394# element properties395#396397def element_tag_name(element)398execute :get_element_tag_name, id: element399end400401def element_attribute(element, name)402WebDriver.logger.debug "Using script for :getAttribute of #{name}", id: :script403execute_atom :getAttribute, element, name404end405406def element_dom_attribute(element, name)407execute :get_element_attribute, id: element, name: name408end409410def element_property(element, name)411execute :get_element_property, id: element, name: name412end413414def element_aria_role(element)415execute :get_element_aria_role, id: element416end417418def element_aria_label(element)419execute :get_element_aria_label, id: element420end421422def element_value(element)423element_property element, 'value'424end425426def element_text(element)427execute :get_element_text, id: element428end429430def element_location(element)431data = execute :get_element_rect, id: element432433Point.new data['x'], data['y']434end435436def element_rect(element)437data = execute :get_element_rect, id: element438439Rectangle.new data['x'], data['y'], data['width'], data['height']440end441442def element_location_once_scrolled_into_view(element)443send_keys_to_element(element, [''])444element_location(element)445end446447def element_size(element)448data = execute :get_element_rect, id: element449450Dimension.new data['width'], data['height']451end452453def element_enabled?(element)454execute :is_element_enabled, id: element455end456457def element_selected?(element)458execute :is_element_selected, id: element459end460461def element_displayed?(element)462WebDriver.logger.debug 'Using script for :isDisplayed', id: :script463execute_atom :isDisplayed, element464end465466def element_value_of_css_property(element, prop)467execute :get_element_css_value, id: element, property_name: prop468end469470#471# finding elements472#473474def active_element475Bridge.element_class.new self, element_id_from(execute(:get_active_element))476end477478alias switch_to_active_element active_element479480def find_element_by(how, what, parent_ref = [])481how, what = @locator_converter.convert(how, what)482483return execute_atom(:findElements, Support::RelativeLocator.new(what).as_json).first if how == 'relative'484485parent_type, parent_id = parent_ref486id = case parent_type487when :element488execute :find_child_element, {id: parent_id}, {using: how, value: what.to_s}489when :shadow_root490execute :find_shadow_child_element, {id: parent_id}, {using: how, value: what.to_s}491else492execute :find_element, {}, {using: how, value: what.to_s}493end494495Bridge.element_class.new self, element_id_from(id)496end497498def find_elements_by(how, what, parent_ref = [])499how, what = @locator_converter.convert(how, what)500501return execute_atom :findElements, Support::RelativeLocator.new(what).as_json if how == 'relative'502503parent_type, parent_id = parent_ref504ids = case parent_type505when :element506execute :find_child_elements, {id: parent_id}, {using: how, value: what.to_s}507when :shadow_root508execute :find_shadow_child_elements, {id: parent_id}, {using: how, value: what.to_s}509else510execute :find_elements, {}, {using: how, value: what.to_s}511end512513ids.map { |id| Bridge.element_class.new self, element_id_from(id) }514end515516def shadow_root(element)517id = execute :get_element_shadow_root, id: element518ShadowRoot.new self, shadow_root_id_from(id)519end520521#522# virtual-authenticator523#524525def add_virtual_authenticator(options)526authenticator_id = execute :add_virtual_authenticator, {}, options.as_json527VirtualAuthenticator.new(self, authenticator_id, options)528end529530def remove_virtual_authenticator(id)531execute :remove_virtual_authenticator, {authenticatorId: id}532end533534def add_credential(credential, id)535execute :add_credential, {authenticatorId: id}, credential536end537538def credentials(authenticator_id)539execute :get_credentials, {authenticatorId: authenticator_id}540end541542def remove_credential(credential_id, authenticator_id)543execute :remove_credential, {credentialId: credential_id, authenticatorId: authenticator_id}544end545546def remove_all_credentials(authenticator_id)547execute :remove_all_credentials, {authenticatorId: authenticator_id}548end549550def user_verified(verified, authenticator_id)551execute :set_user_verified, {authenticatorId: authenticator_id}, {isUserVerified: verified}552end553554#555# federated-credential management556#557558def cancel_fedcm_dialog559execute :cancel_fedcm_dialog560end561562def select_fedcm_account(index)563execute :select_fedcm_account, {}, {accountIndex: index}564end565566def fedcm_dialog_type567execute :get_fedcm_dialog_type568end569570def fedcm_title571execute(:get_fedcm_title).fetch('title')572end573574def fedcm_subtitle575execute(:get_fedcm_title).fetch('subtitle', nil)576end577578def fedcm_account_list579execute :get_fedcm_account_list580end581582def fedcm_delay(enabled)583execute :set_fedcm_delay, {}, {enabled: enabled}584end585586def reset_fedcm_cooldown587execute :reset_fedcm_cooldown588end589590def click_fedcm_dialog_button591execute :click_fedcm_dialog_button, {}, {dialogButton: 'ConfirmIdpLoginContinue'}592end593594def bidi595msg = 'BiDi must be enabled by setting #web_socket_url to true in options class'596raise(WebDriver::Error::WebDriverError, msg)597end598599def command_list600COMMANDS601end602603private604605#606# executes a command on the remote server.607#608# @return [WebDriver::Remote::Response]609#610611def execute(command, opts = {}, command_hash = nil)612verb, path = commands(command) || raise(ArgumentError, "unknown command: #{command.inspect}")613path = path.dup614615path[':session_id'] = session_id if path.include?(':session_id')616617begin618opts.each { |key, value| path[key.inspect] = escaper.escape(value.to_s) }619rescue IndexError620raise ArgumentError, "#{opts.inspect} invalid for #{command.inspect}"621end622623WebDriver.logger.debug("-> #{verb.to_s.upcase} #{path}", id: :command)624http.call(verb, path, command_hash)['value']625end626627def escaper628@escaper ||= defined?(URI::RFC2396_PARSER) ? URI::RFC2396_PARSER : URI::DEFAULT_PARSER629end630631def commands(command)632command_list[command] || Bridge.extra_commands[command]633end634635def unwrap_script_result(arg)636case arg637when Array638arg.map { |e| unwrap_script_result(e) }639when Hash640element_id = element_id_from(arg)641return Bridge.element_class.new(self, element_id) if element_id642643shadow_root_id = shadow_root_id_from(arg)644return ShadowRoot.new self, shadow_root_id if shadow_root_id645646arg.each { |k, v| arg[k] = unwrap_script_result(v) }647else648arg649end650end651652def element_id_from(id)653id['ELEMENT'] || id[Bridge.element_class::ELEMENT_KEY]654end655656def shadow_root_id_from(id)657id[ShadowRoot::ROOT_KEY]658end659660def prepare_capabilities_payload(capabilities)661capabilities = {alwaysMatch: capabilities} if !capabilities['alwaysMatch'] && !capabilities['firstMatch']662{capabilities: capabilities}663end664end # Bridge665end # Remote666end # WebDriver667end # Selenium668669670