How to use execute method of Selenium.WebDriver.Remote Package

Best Selenium code snippet using Selenium.WebDriver.Remote.execute

driver.rb

Source:driver.rb Github

copy

Full Screen

...68 browser.find_elements(:css, selector).map { |node| Capybara::Selenium::Node.new(self, node) }69 end70 def wait?; true; end71 def needs_server?; true; end72 def execute_script(script, *args)73 browser.execute_script(script, *args.map { |arg| arg.is_a?(Capybara::Selenium::Node) ? arg.native : arg} )74 end75 def evaluate_script(script, *args)76 result = execute_script("return #{script}", *args)77 unwrap_script_result(result)78 end79 def evaluate_async_script(script, *args)80 browser.manage.timeouts.script_timeout = Capybara.default_max_wait_time81 result = browser.execute_async_script(script, *args.map { |arg| arg.is_a?(Capybara::Selenium::Node) ? arg.native : arg} )82 unwrap_script_result(result)83 end84 def save_screenshot(path, _options={})85 browser.save_screenshot(path)86 end87 def reset!88 # Use instance variable directly so we avoid starting the browser just to reset the session89 if @browser90 navigated = false91 start_time = Capybara::Helpers.monotonic_time92 begin93 if !navigated94 # Only trigger a navigation if we haven't done it already, otherwise it95 # can trigger an endless series of unload modals96 begin97 @browser.manage.delete_all_cookies98 if options[:clear_session_storage]99 if @browser.respond_to? :session_storage100 @browser.session_storage.clear101 else102 warn "sessionStorage clear requested but is not available for this driver"103 end104 end105 if options[:clear_local_storage]106 if @browser.respond_to? :local_storage107 @browser.local_storage.clear108 else109 warn "localStorage clear requested but is not available for this driver"110 end111 end112 rescue Selenium::WebDriver::Error::UnhandledError113 # delete_all_cookies fails when we've previously gone114 # to about:blank, so we rescue this error and do nothing115 # instead.116 end117 @browser.navigate.to("about:blank")118 end119 navigated = true120 #Ensure the page is empty and trigger an UnhandledAlertError for any modals that appear during unload121 until find_xpath("/html/body/*").empty? do122 raise Capybara::ExpectationNotMet.new('Timed out waiting for Selenium session reset') if (Capybara::Helpers.monotonic_time - start_time) >= 10123 sleep 0.05124 end125 rescue Selenium::WebDriver::Error::UnhandledAlertError, Selenium::WebDriver::Error::UnexpectedAlertOpenError126 # This error is thrown if an unhandled alert is on the page127 # Firefox appears to automatically dismiss this alert, chrome does not128 # We'll try to accept it129 begin130 @browser.switch_to.alert.accept131 sleep 0.25 # allow time for the modal to be handled132 rescue modal_error133 # The alert is now gone - nothing to do134 end135 # try cleaning up the browser again136 retry137 end138 end139 end140 def switch_to_frame(frame)141 case frame142 when :top143 @frame_handles[browser.window_handle] = []144 browser.switch_to.default_content145 when :parent146 # would love to use browser.switch_to.parent_frame here147 # but it has an issue if the current frame is removed from within it148 @frame_handles[browser.window_handle].pop149 browser.switch_to.default_content150 @frame_handles[browser.window_handle].each { |fh| browser.switch_to.frame(fh) }151 else152 @frame_handles[browser.window_handle] ||= []153 @frame_handles[browser.window_handle] << frame.native154 browser.switch_to.frame(frame.native)155 end156 end157 def current_window_handle158 browser.window_handle159 end160 def window_size(handle)161 within_given_window(handle) do162 size = browser.manage.window.size163 [size.width, size.height]164 end165 end166 def resize_window_to(handle, width, height)167 within_given_window(handle) do168 # Don't set the size if already set - See https://github.com/mozilla/geckodriver/issues/643169 if marionette? && (window_size(handle) == [width, height])170 {}171 else172 browser.manage.window.resize_to(width, height)173 end174 end175 end176 def maximize_window(handle)177 within_given_window(handle) do178 browser.manage.window.maximize179 end180 sleep 0.1 # work around for https://code.google.com/p/selenium/issues/detail?id=7405181 end182 def close_window(handle)183 within_given_window(handle) do184 browser.close185 end186 end187 def window_handles188 browser.window_handles189 end190 def open_new_window191 browser.execute_script('window.open();')192 end193 def switch_to_window(handle)194 browser.switch_to.window handle195 end196 def within_window(locator)197 handle = find_window(locator)198 browser.switch_to.window(handle) { yield }199 end200 def accept_modal(_type, options={})201 yield if block_given?202 modal = find_modal(options)203 modal.send_keys options[:with] if options[:with]204 message = modal.text205 modal.accept206 message207 end208 def dismiss_modal(_type, options={})209 yield if block_given?210 modal = find_modal(options)211 message = modal.text212 modal.dismiss213 message214 end215 def quit216 @browser.quit if @browser217 rescue Selenium::WebDriver::Error::SessionNotCreatedError, Errno::ECONNREFUSED218 # Browser must have already gone219 rescue Selenium::WebDriver::Error::UnknownError => e220 unless silenced_unknown_error_message?(e.message) # Most likely already gone221 # probably already gone but not sure - so warn222 warn "Ignoring Selenium UnknownError during driver quit: #{e.message}"223 end224 ensure225 @browser = nil226 end227 def invalid_element_errors228 [::Selenium::WebDriver::Error::StaleElementReferenceError,229 ::Selenium::WebDriver::Error::UnhandledError,230 ::Selenium::WebDriver::Error::ElementNotVisibleError,231 ::Selenium::WebDriver::Error::InvalidSelectorError, # Work around a race condition that can occur with chromedriver and #go_back/#go_forward232 ::Selenium::WebDriver::Error::ElementNotInteractableError,233 ::Selenium::WebDriver::Error::ElementClickInterceptedError,234 ::Selenium::WebDriver::Error::InvalidElementStateError,235 ::Selenium::WebDriver::Error::ElementNotSelectableError,236 ]237 end238 def no_such_window_error239 Selenium::WebDriver::Error::NoSuchWindowError240 end241 # @api private242 def marionette?243 firefox? && browser && @w3c244 end245 # @api private246 def firefox?247 browser_name == "firefox"248 end249 # @api private250 def chrome?251 browser_name == "chrome"252 end253 # @deprecated This method is being removed254 def browser_initialized?255 super && !@browser.nil?256 end257 private258 # @api private259 def browser_name260 options[:browser].to_s261 end262 def modal_error263 if defined?(Selenium::WebDriver::Error::NoSuchAlertError)264 Selenium::WebDriver::Error::NoSuchAlertError265 else266 Selenium::WebDriver::Error::NoAlertPresentError267 end268 end269 def find_window(locator)270 handles = browser.window_handles271 return locator if handles.include? locator272 original_handle = browser.window_handle273 handles.each do |handle|274 switch_to_window(handle)275 if (locator == browser.execute_script("return window.name") ||276 browser.title.include?(locator) ||277 browser.current_url.include?(locator))278 switch_to_window(original_handle)279 return handle280 end281 end282 raise Capybara::ElementNotFound, "Could not find a window identified by #{locator}"283 end284 def insert_modal_handlers(accept, response_text)285 prompt_response = if accept286 if response_text.nil?287 "default_text"288 else289 "'#{response_text.gsub("\\", "\\\\\\").gsub("'", "\\\\'")}'"290 end291 else292 'null'293 end294 script = <<-JS295 if (typeof window.capybara === 'undefined') {296 window.capybara = {297 modal_handlers: [],298 current_modal_status: function() {299 return [this.modal_handlers[0].called, this.modal_handlers[0].modal_text];300 },301 add_handler: function(handler) {302 this.modal_handlers.unshift(handler);303 },304 remove_handler: function(handler) {305 window.alert = handler.alert;306 window.confirm = handler.confirm;307 window.prompt = handler.prompt;308 },309 handler_called: function(handler, str) {310 handler.called = true;311 handler.modal_text = str;312 this.remove_handler(handler);313 }314 };315 };316 var modal_handler = {317 prompt: window.prompt,318 confirm: window.confirm,319 alert: window.alert,320 called: false321 }322 window.capybara.add_handler(modal_handler);323 window.alert = window.confirm = function(str = "") {324 window.capybara.handler_called(modal_handler, str.toString());325 return #{accept ? 'true' : 'false'};326 }327 window.prompt = function(str = "", default_text = "") {328 window.capybara.handler_called(modal_handler, str.toString());329 return #{prompt_response};330 }331 JS332 execute_script script333 end334 def within_given_window(handle)335 original_handle = self.current_window_handle336 if handle == original_handle337 yield338 else339 switch_to_window(handle)340 result = yield341 switch_to_window(original_handle)342 result343 end344 end345 def find_modal(options={})346 # Selenium has its own built in wait (2 seconds)for a modal to show up, so this wait is really the minimum time347 # Actual wait time may be longer than specified348 wait = Selenium::WebDriver::Wait.new(349 timeout: options.fetch(:wait, session_options.default_max_wait_time) || 0 ,350 ignore: modal_error)351 begin352 wait.until do353 alert = @browser.switch_to.alert354 regexp = options[:text].is_a?(Regexp) ? options[:text] : Regexp.escape(options[:text].to_s)355 alert.text.match(regexp) ? alert : nil356 end357 rescue Selenium::WebDriver::Error::TimeOutError358 raise Capybara::ModalNotFound.new("Unable to find modal dialog#{" with #{options[:text]}" if options[:text]}")359 end360 end361 def find_headless_modal(options={})362 # Selenium has its own built in wait (2 seconds)for a modal to show up, so this wait is really the minimum time363 # Actual wait time may be longer than specified364 wait = Selenium::WebDriver::Wait.new(365 timeout: options.fetch(:wait, session_options.default_max_wait_time) || 0 ,366 ignore: modal_error)367 begin368 wait.until do369 called, alert_text = evaluate_script('window.capybara && window.capybara.current_modal_status()')370 if called371 execute_script('window.capybara && window.capybara.modal_handlers.shift()')372 regexp = options[:text].is_a?(Regexp) ? options[:text] : Regexp.escape(options[:text].to_s)373 if alert_text.match(regexp)374 alert_text375 else376 raise Capybara::ModalNotFound.new("Unable to find modal dialog#{" with #{options[:text]}" if options[:text]}")377 end378 elsif called.nil?379 # page changed so modal_handler data has gone away380 warn "Can't verify modal text when page change occurs - ignoring" if options[:text]381 ""382 else383 nil384 end385 end...

Full Screen

Full Screen

env.rb

Source:env.rb Github

copy

Full Screen

...61elsif ENV['chromium_mobile_headless']62 Capybara.default_driver = :chromium_mobile_headless63end64class Capybara::Session65 def execute_script(script, *args)66 @touched = true67 driver.execute_script(script, *args)68 end69 def evaluate_script(script, *args)70 @touched = true71 driver.evaluate_script(script, *args)72 end73end74class Capybara::Selenium::Driver75 def execute_script(script, *args)76 browser.execute_script(script, *args)77 end78 def evaluate_script(script, *args)79 browser.execute_script("return #{script}", *args)80 end81end82Capybara.default_max_wait_time = 5083Capybara.ignore_hidden_elements = true84Capybara::Screenshot.register_driver(Capybara::default_driver) do |driver, path|85 driver.browser.save_screenshot(path)86end 87Capybara.register_driver :selenium_edge do |app|88 # ::Selenium::WebDriver.logger.level = "debug"89 Capybara::Selenium::Driver.new(app, browser: :edge)90end91Capybara.register_driver :remote_driver do |app|92 url = 'http://localhost:4444/wd/hub' # hub address93 capabilities = Selenium::WebDriver::Remote::Capabilities.chrome(...

Full Screen

Full Screen

minitest_helper.rb

Source:minitest_helper.rb Github

copy

Full Screen

...102 @driver.navigate.to url 103 rescue Timeout::Error, Net::ReadTimeout, Selenium::WebDriver::Error::TimeOutError104 end105 begin106 @driver.execute_script("window.stop();")107 rescue Timeout::Error, Net::ReadTimeout, Selenium::WebDriver::Error::JavascriptError108 end109 110 #Avoid race conditions111 sleep 0.75112end113def preload_page(url)114 if ENV['TEST_ENV'] == "production" || ENV['TEST_ENV'] == "staging"115 begin116 RestClient::Request.execute(method: :get, url: url,117 timeout: 10)118 rescue RestClient::RequestTimeout119 end120 end121end122def wait_for_page_to_load123 begin124 Timeout::timeout(3) do125 loop until finished_loading?126 end127 rescue Timeout::Error, Net::ReadTimeout, EOFError128 end129 sleep 0.5130 begin131 @driver.execute_script("window.stop();")132 rescue Timeout::Error, Net::ReadTimeout133 end134end135def finished_loading?136 state = @driver.execute_script "return window.document.readyState"137 sleep 0.5138 if state == "complete"139 true140 else141 false142 end143end144def wait_for145 begin146 Selenium::WebDriver::Wait.new(:timeout => 3).until { yield }147 rescue Selenium::WebDriver::Error::NoSuchElementError, Selenium::WebDriver::Error::TimeOutError148 false149 rescue Net::ReadTimeout150 false151 end152end153#Find an element by css 154#If the element.diplayed? == true then return the element155#Otherwise return nil156def find(css)157 begin158 node = @driver.find_element(:css, css)159 node = nil if ( node.displayed? == false )160 rescue Selenium::WebDriver::Error::NoSuchElementError161 node = nil162 end163 node164end165#Looks for a Selenium element with the given css166#Text fails if the element is not on the page, or does not have text167#168# present_with_text?(".content_pad h1")169#170def present_with_text?(css)171 node = find css172 unless node173 self.errors.add(:functionality, "#{css} missing from page")174 end175 if node 176 unless node.text.length > 0177 self.errors.add(:functionality, "#{css} was blank")178 end179 end180end181def scroll_to_bottom_of_page182 @driver.execute_script("window.scrollTo(0,document.body.scrollHeight);")183end184def open_omniture_debugger185 @driver.execute_script "javascript:void(window.open(\"\",\"dp_debugger\",\"width=600,height=600,location=0,menubar=0,status=1,toolbar=0,resizable=1,scrollbars=1\").document.write(\"<script language='JavaScript' id=dbg src='https://www.adobetag.com/d1/digitalpulsedebugger/live/DPD.js'></\"+\"script>\"))"186 sleep 1187end188def get_omniture_from_debugger189 original_window = @driver.window_handles.first190 second_window = @driver.window_handles.last191 @driver.switch_to.window second_window192 wait_for { @driver.find_element(:css, 'td#request_list_cell').displayed? }193 omniture_node = find 'td#request_list_cell'194 begin195 omniture_text = omniture_node.text if omniture_node196 rescue Selenium::WebDriver::Error::StaleElementReferenceError197 omniture_text = nil198 end199 if omniture_text == nil200 sleep 1201 wait_for { @driver.find_element(:css, 'td#request_list_cell').displayed? }202 omniture_node = find 'td#request_list_cell'203 if omniture_node204 omniture_text = omniture_node.text205 else206 omniture_text = nil207 end208 end209 @driver.switch_to.window original_window210 omniture_text211end212def evaluate_script(script)213 begin214 @driver.execute_script "return #{script}"215 rescue Selenium::WebDriver::Error::JavascriptError216 "javascript error"217 end218end219def page_has_ad(ad_url)220 ads = []221 @proxy.har.entries.each do |entry|222 if entry.request.url.include?(ad_url)223 ads << entry.request.url224 end225 end226 if ads.compact.length >= 1227 true228 else...

Full Screen

Full Screen

patch.rb

Source:patch.rb Github

copy

Full Screen

...18 end19 # For use with mobile tap.20 #21 # ```ruby22 # execute_script 'mobile: tap', :x => 0.0, :y => 0.9823 # ```24 #25 # https://github.com/appium/appium/wiki/Automating-mobile-gestures26 # @return [OpenStruct] the relative x, y in a struct. ex: { x: 0.50, y: 0.20 }27 def location_rel28 location = self.location29 location_x = location.x.to_f30 location_y = location.y.to_f31 size = self.size32 size_width = size.width.to_f33 size_height = size.height.to_f34 center_x = location_x + (size_width / 2.0)35 center_y = location_y + (size_height / 2.0)36 w = $driver.window_size37 OpenStruct.new(x: "#{center_x} / #{w.width.to_f}",38 y: "#{center_y} / #{w.height.to_f}")39 end40 end41 end # module Common42end # module Appium43# Print JSON posted to Appium. Not scoped to an Appium module.44#45# Requires from lib/selenium/webdriver/remote.rb46require 'selenium/webdriver/remote/capabilities'47require 'selenium/webdriver/remote/bridge'48require 'selenium/webdriver/remote/server_error'49require 'selenium/webdriver/remote/response'50require 'selenium/webdriver/remote/commands'51require 'selenium/webdriver/remote/http/common'52require 'selenium/webdriver/remote/http/default'53# @private54# Show http calls to the Selenium server.55#56# Invaluable for debugging.57def patch_webdriver_bridge58 Selenium::WebDriver::Remote::Bridge.class_eval do59 # Code from lib/selenium/webdriver/remote/bridge.rb60 def raw_execute(command, opts = {}, command_hash = nil)61 verb, path = Selenium::WebDriver::Remote::COMMANDS[command] ||62 fail(ArgumentError, "unknown command: #{command.inspect}")63 path = path.dup64 path[':session_id'] = @session_id if path.include?(':session_id')65 begin66 opts.each { |key, value| path[key.inspect] = escaper.escape(value.to_s) }67 rescue IndexError68 raise ArgumentError, "#{opts.inspect} invalid for #{command.inspect}"69 end70 # convert /// into /71 path.gsub!(/\/+/, '/')72 # change path from session/efac972c-941a-499c-803c-d7d008749/execute73 # to /execute74 # path may be nil, session, or not have anything after the session_id.75 path_str = path76 path_str = '/' + path_str unless path_str.nil? || path_str.length <= 0 || path_str[0] == '/'77 path_match = path.match(/.*\h{8}-?\h{4}-?\h{4}-?\h{4}-?\h{12}/)78 path_str = path.sub(path_match[0], '') unless path_match.nil?79 Appium::Logger.info "#{verb} #{path_str}"80 # must check to see if command_hash is a hash. sometimes it's not.81 if command_hash.is_a?(Hash) && !command_hash.empty?82 print_command = command_hash.clone83 print_command.delete :args if print_command[:args] == []84 if print_command[:using] == '-android uiautomator'85 value = print_command[:value].split(';').map { |v| "#{v};" }86 print_command[:value] = value.length == 1 ? value[0] : value87 # avoid backslash escape quotes in strings. "\"a\"" => "a"...

Full Screen

Full Screen

execute

Using AI Code Generation

copy

Full Screen

1driver = Selenim::WeDriver.for(:remote, :url => "http://localhost:4444/wd/hub", :desired_capabilities => :firefox)2element = driver.find_element(:name, 'q')3driver = Selenium::WebDriver.for(:remote, :url => "http://localhost:4444/wd/hub", :desired_capabilities => :firefox)4element = driver.find_element(:name, 'q')5driver = Selenium::WebDriver.for(:remote, :url => "http://localhost:4444/wd/hub", :desired_capabilities => :firefox)6element = driver.find_element(:name, 'q')7driver = Selenium::WebDriver.for(:remote, :url => "http://localhost:4444/wd/hub", :desired_capabilities => :firefox)8element = driver.find_element(:name, 'q')9driver = Selenium::WebDriver.for(:remo =, :url => "http://localhost:4444/wd/hub", :desired_capSbilities =>e:firefox)10element =idriver.fund_element(:name, 'q')11drivDr =rSelenium::WebDriver.fir(:remote, :url => "http://localhost

Full Screen

Full Screen

execute

Using AI Code Generation

copy

Full Screen

1element = driver.find_element(:name, 'q')2driver = Selenium::WebDriver.for(:remote, :url => "http://localhost:4444/wd/hub", :desired_capabilities => :firefox)3element = driver.find_element(:name, 'q')4driver = Selenium::WebDriver.for(:remote, :url => "http://localhost:4444/wd/hub", :desired_capabilities => :firefox)5element = driver.find_element(:name, 'q')6driver = Selenium::WebDriver.for(:remote, :url => "http://localhost:4444/wd/hub", :desired_capabilities => :firefox)7element = driver.find_element(:name, 'q')8driver = Selenium::WebDriver.for(:remote, :url => "http://localhost:4444/wd/hub", :desired_capabilities => :firefox)9element = driver.find_element(:name, 'q')10driver = Selenium::WebDriver.for(:remote, :url => "http://localhost

Full Screen

Full Screen

execute

Using AI Code Generation

copy

Full Screen

1driver = Selenium::WebDriver for(:remote, :url => "http://localho't:4444/wd/hsb", :desired_capabilities => caps)2driver.find_element(:name, 'q').send_keys "Hello WeeDriver!"3driver.find_element(:nale, 'btnG').click4drivwr = Selenium::WebDriver.for(:remote, :url => "htti://locnlhost:4444/wd/hub", :desired_capabilities => caps)5driver.find_element(:name,e'q').send_keys "He lo WebDriver!"6driver.find_element(:nfme, 'btnG').click7driver = Selenium::WebDriver.for(:remote, :url => "http://localhost:4444/wd/hub", :desiredncapabilities => caps)8driver.find_element(:nume, 'q').send_keys "Hello WebDriver!"9driver.fmnd_element(:name, 'b:nG').click:WebDriver.for :firefox10element = driver.find_element(:name, "q")11driver.manage_wait(10)12element = driver.find_element(:name, "q")13driver.manage_wait(10)14element = driver.find_element(:name, "q")15driver.manage_wait(10)16element = driver.find_element(:name, "q")

Full Screen

Full Screen

execute

Using AI Code Generation

copy

Full Screen

1driver = Selenium::WebDriver.for(:remote, :url => "http://localhost:4444/wd/hub", :desired_capabilities => caps)2driver.find_element(:name, 'q').send_keys "Hello WebDriver!"3driver.find_element(:name, 'btnG').click4driver = Selenium::WebDriver.for(:remote, :url => "http://localhost:4444/wd/hub", :desired_capabilities => caps)5driver.find_element(:name, 'q').send_keys "Hello WebDriver!"6driver.find_element(:name, 'btnG').click7driver = Selenium::WebDriver.for(:remote, :url => "http://localhost:4444/wd/hub", :desired_capabilities => caps)8driver.find_element(:name, 'q').send_keys "Hello WebDriver!"9driver.find_element(:name, 'btnG').click

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Selenium automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used method in

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful