Best Selenium code snippet using Selenium.WebDriver.alert
driver.rb
Source:driver.rb
...137 reset_browser_state unless navigated138 navigated = true139 # Ensure the page is empty and trigger an UnhandledAlertError for any modals that appear during unload140 wait_for_empty_page(timer)141 rescue *unhandled_alert_errors142 # This error is thrown if an unhandled alert is on the page143 # Firefox appears to automatically dismiss this alert, chrome does not144 # We'll try to accept it145 accept_unhandled_reset_alert146 # try cleaning up the browser again147 retry148 end149 end150 def frame_obscured_at?(x:, y:)151 frame = @frame_handles[current_window_handle].last152 return false unless frame153 switch_to_frame(:parent)154 begin155 frame.base.obscured?(x: x, y: y)156 ensure157 switch_to_frame(frame)158 end159 end160 def switch_to_frame(frame)161 handles = @frame_handles[current_window_handle]162 case frame163 when :top164 handles.clear165 browser.switch_to.default_content166 when :parent167 handles.pop168 browser.switch_to.parent_frame169 else170 handles << frame171 browser.switch_to.frame(frame.native)172 end173 end174 def current_window_handle175 browser.window_handle176 end177 def window_size(handle)178 within_given_window(handle) do179 size = browser.manage.window.size180 [size.width, size.height]181 end182 end183 def resize_window_to(handle, width, height)184 within_given_window(handle) do185 browser.manage.window.resize_to(width, height)186 end187 end188 def maximize_window(handle)189 within_given_window(handle) do190 browser.manage.window.maximize191 end192 sleep 0.1 # work around for https://code.google.com/p/selenium/issues/detail?id=7405193 end194 def fullscreen_window(handle)195 within_given_window(handle) do196 browser.manage.window.full_screen197 end198 end199 def close_window(handle)200 raise ArgumentError, 'Not allowed to close the primary window' if handle == window_handles.first201 within_given_window(handle) do202 browser.close203 end204 end205 def window_handles206 browser.window_handles207 end208 def open_new_window(kind = :tab)209 browser.manage.new_window(kind)210 rescue NoMethodError, Selenium::WebDriver::Error::WebDriverError211 # If not supported by the driver or browser default to using JS212 browser.execute_script('window.open();')213 end214 def switch_to_window(handle)215 browser.switch_to.window handle216 end217 def accept_modal(_type, **options)218 yield if block_given?219 modal = find_modal(**options)220 modal.send_keys options[:with] if options[:with]221 message = modal.text222 modal.accept223 message224 end225 def dismiss_modal(_type, **options)226 yield if block_given?227 modal = find_modal(**options)228 message = modal.text229 modal.dismiss230 message231 end232 def quit233 @browser&.quit234 rescue Selenium::WebDriver::Error::SessionNotCreatedError, Errno::ECONNREFUSED,235 Selenium::WebDriver::Error::InvalidSessionIdError236 # Browser must have already gone237 rescue Selenium::WebDriver::Error::UnknownError => e238 unless silenced_unknown_error_message?(e.message) # Most likely already gone239 # probably already gone but not sure - so warn240 warn "Ignoring Selenium UnknownError during driver quit: #{e.message}"241 end242 ensure243 @browser = nil244 end245 def invalid_element_errors246 @invalid_element_errors ||= begin247 [248 ::Selenium::WebDriver::Error::StaleElementReferenceError,249 ::Selenium::WebDriver::Error::ElementNotInteractableError,250 ::Selenium::WebDriver::Error::InvalidSelectorError, # Work around chromedriver go_back/go_forward race condition251 ::Selenium::WebDriver::Error::ElementClickInterceptedError,252 ::Selenium::WebDriver::Error::NoSuchElementError, # IE253 ::Selenium::WebDriver::Error::InvalidArgumentError # IE254 ].tap do |errors|255 unless selenium_4?256 ::Selenium::WebDriver.logger.suppress_deprecations do257 errors.concat [258 ::Selenium::WebDriver::Error::UnhandledError,259 ::Selenium::WebDriver::Error::ElementNotVisibleError,260 ::Selenium::WebDriver::Error::InvalidElementStateError,261 ::Selenium::WebDriver::Error::ElementNotSelectableError262 ]263 end264 end265 end266 end267 end268 def no_such_window_error269 Selenium::WebDriver::Error::NoSuchWindowError270 end271private272 def selenium_4?273 defined?(Selenium::WebDriver::VERSION) && (Selenium::WebDriver::VERSION.to_f >= 4)274 end275 def native_args(args)276 args.map { |arg| arg.is_a?(Capybara::Selenium::Node) ? arg.native : arg }277 end278 def clear_browser_state279 delete_all_cookies280 clear_storage281 rescue *clear_browser_state_errors282 # delete_all_cookies fails when we've previously gone283 # to about:blank, so we rescue this error and do nothing284 # instead.285 end286 def clear_browser_state_errors287 @clear_browser_state_errors ||= [Selenium::WebDriver::Error::UnknownError]288 end289 def unhandled_alert_errors290 @unhandled_alert_errors ||= with_legacy_error(291 [Selenium::WebDriver::Error::UnexpectedAlertOpenError],292 'UnhandledAlertError'293 )294 end295 def delete_all_cookies296 @browser.manage.delete_all_cookies297 end298 def clear_storage299 clear_session_storage unless options[:clear_session_storage] == false300 clear_local_storage unless options[:clear_local_storage] == false301 rescue Selenium::WebDriver::Error::JavascriptError302 # session/local storage may not be available if on non-http pages (e.g. about:blank)303 end304 def clear_session_storage305 if @browser.respond_to? :session_storage306 @browser.session_storage.clear307 else308 begin309 @browser&.execute_script('window.sessionStorage.clear()')310 rescue # rubocop:disable Style/RescueStandardError311 unless options[:clear_session_storage].nil?312 warn 'sessionStorage clear requested but is not supported by this driver'313 end314 end315 end316 end317 def clear_local_storage318 if @browser.respond_to? :local_storage319 @browser.local_storage.clear320 else321 begin322 @browser&.execute_script('window.localStorage.clear()')323 rescue # rubocop:disable Style/RescueStandardError324 unless options[:clear_local_storage].nil?325 warn 'localStorage clear requested but is not supported by this driver'326 end327 end328 end329 end330 def navigate_with_accept(url)331 @browser.navigate.to(url)332 sleep 0.1 # slight wait for alert333 @browser.switch_to.alert.accept334 rescue modal_error335 # alert now gone, should mean navigation happened336 end337 def modal_error338 Selenium::WebDriver::Error::NoSuchAlertError339 end340 def within_given_window(handle)341 original_handle = current_window_handle342 if handle == original_handle343 yield344 else345 switch_to_window(handle)346 result = yield347 switch_to_window(original_handle)348 result349 end350 end351 def find_modal(text: nil, **options)352 # Selenium has its own built in wait (2 seconds)for a modal to show up, so this wait is really the minimum time353 # Actual wait time may be longer than specified354 wait = Selenium::WebDriver::Wait.new(355 timeout: options.fetch(:wait, session_options.default_max_wait_time) || 0,356 ignore: modal_error357 )358 begin359 wait.until do360 alert = @browser.switch_to.alert361 regexp = text.is_a?(Regexp) ? text : Regexp.new(Regexp.escape(text.to_s))362 matched = alert.text.match?(regexp)363 unless matched364 raise Capybara::ModalNotFound, "Unable to find modal dialog with #{text} - found '#{alert.text}' instead."365 end366 alert367 end368 rescue *find_modal_errors369 raise Capybara::ModalNotFound, "Unable to find modal dialog#{" with #{text}" if text}"370 end371 end372 def find_modal_errors373 @find_modal_errors ||= with_legacy_error([Selenium::WebDriver::Error::TimeoutError], 'TimeOutError')374 end375 def with_legacy_error(errors, legacy_error)376 errors.tap do |errs|377 unless selenium_4?378 ::Selenium::WebDriver.logger.suppress_deprecations do379 errs << Selenium::WebDriver::Error.const_get(legacy_error)380 end381 end382 end383 end384 def silenced_unknown_error_message?(msg)385 silenced_unknown_error_messages.any? { |regex| msg.match? regex }386 end387 def silenced_unknown_error_messages388 [/Error communicating with the remote browser/]389 end390 def unwrap_script_result(arg)391 case arg392 when Array393 arg.map { |arr| unwrap_script_result(arr) }394 when Hash395 arg.transform_values! { |value| unwrap_script_result(value) }396 when Selenium::WebDriver::Element397 build_node(arg)398 else399 arg400 end401 end402 def find_context403 browser404 end405 def active_element406 browser.switch_to.active_element407 end408 def build_node(native_node, initial_cache = {})409 ::Capybara::Selenium::Node.new(self, native_node, initial_cache)410 end411 def bridge412 browser.send(:bridge)413 end414 def specialize_driver415 browser_type = browser.browser416 Capybara::Selenium::Driver.specializations.select { |k, _v| k === browser_type }.each_value do |specialization| # rubocop:disable Style/CaseEquality417 extend specialization418 end419 end420 def setup_exit_handler421 main = Process.pid422 at_exit do423 # Store the exit status of the test run since it goes away after calling the at_exit proc...424 @exit_status = $ERROR_INFO.status if $ERROR_INFO.is_a?(SystemExit)425 quit if Process.pid == main426 exit @exit_status if @exit_status # Force exit with stored status427 end428 end429 def reset_browser_state430 clear_browser_state431 @browser.navigate.to('about:blank')432 end433 def wait_for_empty_page(timer)434 until find_xpath('/html/body/*').empty?435 raise Capybara::ExpectationNotMet, 'Timed out waiting for Selenium session reset' if timer.expired?436 sleep 0.01437 # It has been observed that it is possible that asynchronous JS code in438 # the application under test can navigate the browser away from about:blank439 # if the timing is just right. Ensure we are still at about:blank...440 @browser.navigate.to('about:blank') unless current_url == 'about:blank'441 end442 end443 def accept_unhandled_reset_alert444 @browser.switch_to.alert.accept445 sleep 0.25 # allow time for the modal to be handled446 rescue modal_error447 # The alert is now gone.448 # If navigation has not occurred attempt again and accept alert449 # since FF may have dismissed the alert at first attempt.450 navigate_with_accept('about:blank') if current_url != 'about:blank'451 end452end453require 'capybara/selenium/driver_specializations/chrome_driver'454require 'capybara/selenium/driver_specializations/firefox_driver'455require 'capybara/selenium/driver_specializations/internet_explorer_driver'456require 'capybara/selenium/driver_specializations/safari_driver'457require 'capybara/selenium/driver_specializations/edge_driver'...
alert
Using AI Code Generation
1driver.find_element(:name, 'q').send_keys "Selenium WebDriver"2driver.find_element(:name, 'btnG').click3driver.find_element(:name, 'q').send_keys "Selenium WebDriver"4driver.find_element(:name, 'btnG').click5driver.find_element(:name, 'q').send_keys "Selenium WebDriver"6driver.find_element(:name, 'btnG').click
alert
Using AI Code Generation
1driver.find_element(:name, 'q').send_keys "Selenium WebDriver"2driver.find_element(:name, 'btnG').click3driver.find_element(:name, 'q').send_keys "Selenium WebDriver"4driver.find_element(:name, 'btnG').click5driver.find_element(:name, 'q').send_keys "Selenium WebDriver"6driver.find_element(:name, 'btnG').click7driver.find_element(:name, 'q').send_keys "Selenium WebDriver"8driver.find_element(:name, 'btnG').click9driver.find_element(:name, 'q').send_keys "Selenium WebDriver"10driver.find_element(:name, 'btnG').click11driver.find_element(:name, 'q').clear12driver.find_element(:name, 'q').send_keys "Selenium WebDriver Tutorial"13driver.find_element(:name, 'btnG').click
alert
Using AI Code Generation
1driver.find_element(:name, 'q').send_keys "Selenium WebDriver"2driver.find_element(:name, 'btnG').click3wait = Selenium::WebDriver::Wait.new(:timeout => 10)4wait.until { driver.title.downcase.start_with? "selenium webdriver" }5driver.find_element(:name, 'q').send_keys "Selenium WebDriver"6driver.find_element(:name, 'btnG').click7wait = Selenium::WebDriver::Wait.new(:timeout => 10)8wait.until { driver.title.downcase.start_with? "selenium webdriver" }
alert
Using AI Code Generation
1driver.find_element(:name, "q").send_keys "Selenium WebDriver"2driver.find_element(:name, "btnG").click3Selenium WebDriver is a collection of libraries that are used to automate web browsers. It is used to automate web applications for testing purposes, but is not limited to just that. Boring web-based administration tasks can (and should!) also
alert
Using AI Code Generation
1driver.find_element(:name, "q").send_keys "Hello World"2driver.find_element(:name, "btnK").click3driver.find_element(:name, 'q').send_keys "Selenium WebDriver"4driver.find_element(:name, 'btnG').click5driver.find_element(:name, 'q').send_keys "Selenium WebDriver"6driver.find_element(:name, 'btnG').click7driver.find_element(:name, 'q').clear8driver.find_element(:name, 'q').send_keys "Selenium WebDriver Tutorial"9driver.find_element(:name, 'btnG').click
alert
Using AI Code Generation
1driver.find_element(:name, 'q').send_keys "Selenium WebDriver"2driver.find_element(:name, 'btnG').click3wait = Selenium::WebDriver::Wait.new(:timeout => 10)4wait.until { driver.title.downcase.start_with? "selenium webdriver" }5driver.find_element(:name, 'q').send_keys "Selenium WebDriver"6driver.find_element(:name, 'btnG').click7wait = Selenium::WebDriver::Wait.new(:timeout => 10)8wait.until { driver.title.downcase.start_with? "selenium webdriver" }
alert
Using AI Code Generation
1driver.find_element(:name, "q").send_keys "Selenium WebDriver"2driver.find_element(:name, "btnG").click3Selenium WebDriver is a collection of libraries that are used to automate web browsers. It is used to automate web applications for testing purposes, but is not limited to just that. Boring web-based administration tasks can (and should!) also
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!