How to use window_handles method of Selenium.WebDriver Package

Best Selenium code snippet using Selenium.WebDriver.window_handles

driver.rb

Source:driver.rb Github

copy

Full Screen

...98 def reset!99 # Use instance variable directly so we avoid starting the browser just to reset the session100 return unless @browser101 if firefox? || chrome?102 switch_to_window(window_handles.first)103 window_handles.slice(1..-1).each { |win| close_window(win) }104 end105 navigated = false106 start_time = Capybara::Helpers.monotonic_time107 begin108 unless navigated109 # Only trigger a navigation if we haven't done it already, otherwise it110 # can trigger an endless series of unload modals111 begin112 @browser.manage.delete_all_cookies113 clear_storage114 # rescue Selenium::WebDriver::Error::NoSuchAlertError115 # # Handle a bug in Firefox/Geckodriver where it thinks it needs an alert modal to exist116 # # for no good reason117 # retry118 rescue Selenium::WebDriver::Error::UnhandledError # rubocop:disable Lint/HandleExceptions119 # delete_all_cookies fails when we've previously gone120 # to about:blank, so we rescue this error and do nothing121 # instead.122 end123 @browser.navigate.to("about:blank")124 end125 navigated = true126 # Ensure the page is empty and trigger an UnhandledAlertError for any modals that appear during unload127 until find_xpath("/html/body/*").empty?128 raise Capybara::ExpectationNotMet, 'Timed out waiting for Selenium session reset' if (Capybara::Helpers.monotonic_time - start_time) >= 10129 sleep 0.05130 end131 rescue Selenium::WebDriver::Error::UnhandledAlertError, Selenium::WebDriver::Error::UnexpectedAlertOpenError132 # This error is thrown if an unhandled alert is on the page133 # Firefox appears to automatically dismiss this alert, chrome does not134 # We'll try to accept it135 begin136 @browser.switch_to.alert.accept137 sleep 0.25 # allow time for the modal to be handled138 rescue modal_error139 # The alert is now gone140 if current_url != "about:blank"141 begin142 # If navigation has not occurred attempt again and accept alert143 # since FF may have dismissed the alert at first attempt144 @browser.navigate.to("about:blank")145 sleep 0.1 # slight wait for alert146 @browser.switch_to.alert.accept147 rescue modal_error # rubocop:disable Metrics/BlockNesting, Lint/HandleExceptions148 # alert now gone, should mean navigation happened149 end150 end151 end152 # try cleaning up the browser again153 retry154 end155 end156 def switch_to_frame(frame)157 case frame158 when :top159 @frame_handles[browser.window_handle] = []160 browser.switch_to.default_content161 when :parent162 # would love to use browser.switch_to.parent_frame here163 # but it has an issue if the current frame is removed from within it164 @frame_handles[browser.window_handle].pop165 browser.switch_to.default_content166 @frame_handles[browser.window_handle].each { |fh| browser.switch_to.frame(fh) }167 else168 @frame_handles[browser.window_handle] ||= []169 @frame_handles[browser.window_handle] << frame.native170 browser.switch_to.frame(frame.native)171 end172 end173 def current_window_handle174 browser.window_handle175 end176 def window_size(handle)177 within_given_window(handle) do178 size = browser.manage.window.size179 [size.width, size.height]180 end181 end182 def resize_window_to(handle, width, height)183 within_given_window(handle) do184 # Don't set the size if already set - See https://github.com/mozilla/geckodriver/issues/643185 if marionette? && (window_size(handle) == [width, height])186 {}187 else188 browser.manage.window.resize_to(width, height)189 end190 end191 end192 def maximize_window(handle)193 within_given_window(handle) do194 browser.manage.window.maximize195 end196 sleep 0.1 # work around for https://code.google.com/p/selenium/issues/detail?id=7405197 end198 def close_window(handle)199 raise ArgumentError, "Not allowed to close the primary window" if handle == window_handles.first200 within_given_window(handle) do201 browser.close202 end203 end204 def window_handles205 browser.window_handles206 end207 def open_new_window208 browser.execute_script('window.open();')209 end210 def switch_to_window(handle)211 browser.switch_to.window handle212 end213 def accept_modal(_type, **options)214 yield if block_given?215 modal = find_modal(options)216 modal.send_keys options[:with] if options[:with]217 message = modal.text218 modal.accept219 message...

Full Screen

Full Screen

target_locator_spec.rb

Source:target_locator_spec.rb Github

copy

Full Screen

...20 describe TargetLocator do21 after do22 ensure_single_window23 end24 let(:new_window) { driver.window_handles.find { |handle| handle != driver.window_handle } }25 # Safari is using GET instead of POST (W3C vs JWP)26 # Server - https://github.com/SeleniumHQ/selenium/issues/179527 it 'should find the active element', except: {driver: :remote, browser: :edge} do28 driver.navigate.to url_for('xhtmlTest.html')29 expect(driver.switch_to.active_element).to be_an_instance_of(WebDriver::Element)30 end31 # Doesn't switch to frame by id directly32 it 'should switch to a frame directly', except: {browser: %i[safari safari_preview]} do33 driver.navigate.to url_for('iframes.html')34 driver.switch_to.frame('iframe1')35 expect(driver.find_element(name: 'login')).to be_kind_of(WebDriver::Element)36 end37 it 'should switch to a frame by Element' do38 driver.navigate.to url_for('iframes.html')39 iframe = driver.find_element(tag_name: 'iframe')40 driver.switch_to.frame(iframe)41 expect(driver.find_element(name: 'login')).to be_kind_of(WebDriver::Element)42 end43 it 'should switch to parent frame' do44 driver.navigate.to url_for('iframes.html')45 iframe = driver.find_element(tag_name: 'iframe')46 driver.switch_to.frame(iframe)47 expect(driver.find_element(name: 'login')).to be_kind_of(WebDriver::Element)48 driver.switch_to.parent_frame49 expect(driver.find_element(id: 'iframe_page_heading')).to be_kind_of(WebDriver::Element)50 end51 context 'window switching' do52 after do53 sleep 1 if ENV['TRAVIS']54 quit_driver55 end56 it 'should switch to a window and back when given a block' do57 driver.navigate.to url_for('xhtmlTest.html')58 driver.find_element(link: 'Open new window').click59 wait.until { driver.window_handles.size == 2 }60 expect(driver.title).to eq('XHTML Test Page')61 driver.switch_to.window(new_window) do62 wait.until { driver.title == 'We Arrive Here' }63 end64 wait.until { driver.title == 'XHTML Test Page' }65 end66 it 'should handle exceptions inside the block' do67 driver.navigate.to url_for('xhtmlTest.html')68 driver.find_element(link: 'Open new window').click69 wait.until { driver.window_handles.size == 2 }70 expect(driver.title).to eq('XHTML Test Page')71 expect do72 driver.switch_to.window(new_window) { raise 'foo' }73 end.to raise_error(RuntimeError, 'foo')74 expect(driver.title).to eq('XHTML Test Page')75 end76 it 'should switch to a window without a block' do77 driver.navigate.to url_for('xhtmlTest.html')78 driver.find_element(link: 'Open new window').click79 wait.until { driver.window_handles.size == 2 }80 expect(driver.title).to eq('XHTML Test Page')81 driver.switch_to.window(new_window)82 wait.until { driver.title == 'We Arrive Here' }83 expect(driver.title).to eq('We Arrive Here')84 end85 it 'should use the original window if the block closes the popup' do86 driver.navigate.to url_for('xhtmlTest.html')87 driver.find_element(link: 'Open new window').click88 wait.until { driver.window_handles.size == 2 }89 expect(driver.title).to eq('XHTML Test Page')90 driver.switch_to.window(new_window) do91 wait.until { driver.title == 'We Arrive Here' }92 driver.close93 end94 expect(driver.current_url).to include('xhtmlTest.html')95 expect(driver.title).to eq('XHTML Test Page')96 end97 end98 context 'with more than two windows', except: {browser: %i[ie safari safari_preview]} do99 after do100 # We need to reset driver because browsers behave differently101 # when trying to open the same blank target in a new window.102 # Sometimes it's opened in a new window (Firefox 55), sometimes103 # in the same window (Firefox 57). In any event, this has nothing104 # to do with Selenium test.105 sleep 1 if ENV['TRAVIS']106 reset_driver!107 end108 it 'should close current window when more than two windows exist' do109 driver.navigate.to url_for('xhtmlTest.html')110 wait_for_element(link: 'Create a new anonymous window')111 driver.find_element(link: 'Create a new anonymous window').click112 wait.until { driver.window_handles.size == 2 }113 driver.find_element(link: 'Open new window').click114 wait.until { driver.window_handles.size == 3 }115 driver.switch_to.window(driver.window_handle) { driver.close }116 expect(driver.window_handles.size).to eq 2117 end118 it 'should close another window when more than two windows exist' do119 driver.navigate.to url_for('xhtmlTest.html')120 wait_for_element(link: 'Create a new anonymous window')121 driver.find_element(link: 'Create a new anonymous window').click122 wait.until { driver.window_handles.size == 2 }123 driver.find_element(link: 'Open new window').click124 wait.until { driver.window_handles.size == 3 }125 window_to_close = driver.window_handles.last126 driver.switch_to.window(window_to_close) { driver.close }127 expect(driver.window_handles.size).to eq 2128 end129 it 'should iterate over open windows when current window is not closed' do130 driver.navigate.to url_for('xhtmlTest.html')131 wait_for_element(link: 'Create a new anonymous window')132 driver.find_element(link: 'Create a new anonymous window').click133 wait.until { driver.window_handles.size == 2 }134 driver.find_element(link: 'Open new window').click135 wait.until { driver.window_handles.size == 3 }136 titles = {}137 driver.window_handles.each do |wh|138 driver.switch_to.window(wh) { titles[driver.title] = driver.window_handle }139 end140 handle = titles['We Arrive Here']141 driver.switch_to.window(handle)142 expect(driver.title).to eq('We Arrive Here')143 end144 it 'should iterate over open windows when current window is closed' do145 driver.navigate.to url_for('xhtmlTest.html')146 wait_for_element(link: 'Create a new anonymous window')147 driver.find_element(link: 'Create a new anonymous window').click148 wait.until { driver.window_handles.size == 2 }149 driver.find_element(link: 'Open new window').click150 wait.until { driver.window_handles.size == 3 }151 driver.close152 titles = {}153 driver.window_handles.each do |wh|154 driver.switch_to.window(wh) { titles[driver.title] = wh }155 end156 handle = titles['We Arrive Here']157 driver.switch_to.window(handle)158 expect(driver.title).to eq('We Arrive Here')159 end160 end161 it 'should switch to a window and execute a block when current window is closed' do162 driver.navigate.to url_for('xhtmlTest.html')163 driver.find_element(link: 'Open new window').click164 wait.until { driver.window_handles.size == 2 }165 driver.switch_to.window(new_window)166 wait.until { driver.title == 'We Arrive Here' }167 driver.close168 driver.switch_to.window(driver.window_handles.first) do169 wait.until { driver.title == 'XHTML Test Page' }170 end171 expect(driver.title).to eq('XHTML Test Page')172 end173 it 'should switch to default content' do174 driver.navigate.to url_for('iframes.html')175 driver.switch_to.frame 0176 driver.switch_to.default_content177 driver.find_element(id: 'iframe_page_heading')178 end179 # Edge BUG - https://connect.microsoft.com/IE/feedback/details/1850030180 describe 'alerts' do181 it 'allows the user to accept an alert' do182 driver.navigate.to url_for('alerts.html')...

Full Screen

Full Screen

user_operation_helper.rb

Source:user_operation_helper.rb Github

copy

Full Screen

...35 def refresh(_)36 @driver.navigate.refresh37 end38 def switch_to_next_window(_)39 window_index = @driver.window_handles.index(@driver.window_handle)40 windows_number = @driver.window_handles.size41 unless window_index+1 == windows_number42 @driver.switch_to.window(@driver.window_handles[window_index+1])43 end44 end45 def switch_to_previous_window(_)46 window_index = @driver.window_handles.index(@driver.window_handle)47 @driver.switch_to.window(@driver.window_handles[window_index-1])48 end49 def switch_to_newest_window(_)50 @driver.switch_to.window(@driver.window_handles.last)51 end52 def switch_to_oldest_window(_)53 @driver.switch_to.window(@driver.window_handles.first)54 end55 def switch_to_the_window(args)56 # when the window successfully switched, return of switch_to.window is nil.57 wait_until_helper(5, 0.1, Selenium::WebDriver::Error::NoSuchWindowError) { @driver.switch_to.window(args[:window_name]).nil? }58 end59 # Close window60 def close(_)61 window_index = @driver.window_handles.index(@driver.window_handle)62 @driver.close63 @driver.switch_to.window(@driver.window_handles[window_index-1])64 end65 def stop(_)66 puts 'stop. press enter to continue'67 gets68 end69 def choose(args)70 option = wait_until_helper(5, 0.1, Selenium::WebDriver::Error::StaleElementReferenceError) { Selenium::WebDriver::Support::Select.new(@pages.get_part(args)) }71 if args.key?(:text)72 type = :text73 selected = args[type].to_s74 elsif args.key?(:value)75 type = :value76 selected = args[type].to_s77 elsif args.key?(:index)...

Full Screen

Full Screen

web_driver_utils.rb

Source:web_driver_utils.rb Github

copy

Full Screen

...80 end81 def self.verify_external_link(driver, link, expected_page_title)82 begin83 link.click84 if driver.window_handles.length > 185 driver.switch_to.window driver.window_handles.last86 wait = Selenium::WebDriver::Wait.new(:timeout => WebDriverUtils.page_load_timeout)87 wait.until { driver.find_element(:xpath => "//title[contains(.,'#{expected_page_title}')]") }88 true89 else90 logger.error('Link did not open in a new window')91 false92 end93 rescue94 false95 ensure96 if driver.window_handles.length > 197 # Handle any alert that might appear when opening the new window98 driver.switch_to.alert.accept rescue Selenium::WebDriver::Error::NoAlertPresentError99 driver.close100 # Handle any alert that might appear when closing the new window101 driver.switch_to.alert.accept rescue Selenium::WebDriver::Error::NoAlertPresentError102 end103 driver.switch_to.window driver.window_handles.first104 end105 end106end...

Full Screen

Full Screen

firefox_driver.rb

Source:firefox_driver.rb Github

copy

Full Screen

...41 rescue Selenium::WebDriver::Error::NoSuchAlertError42 # Swallow43 end44 end45 switch_to_window(window_handles.first)46 window_handles.slice(1..).each { |win| close_window(win) }47 super48 end49 def refresh50 # Accept any "will repost content" confirmation that occurs51 accept_modal :confirm, wait: 0.1 do52 super53 end54 rescue Capybara::ModalNotFound55 # No modal was opened - page has refreshed - ignore56 end57 def switch_to_frame(frame)58 return super unless frame == :parent59 # geckodriver/firefox has an issue if the current frame is removed from within it60 # so we have to move to the default_content and iterate back through the frames...

Full Screen

Full Screen

testcase2_spec.rb

Source:testcase2_spec.rb Github

copy

Full Screen

...10 @driver.quit11 end12 def wait_for_window(self, timeout = 2):13 sleep(round(timeout / 1000))14 wh_now = @driver.window_handles15 wh_then = @vars['window_handles']16 wh_now.find { |window| window != wh_then.first17 end18 it 'testcase2' do19 # Test name: Testcase220 # Step # | name | target | value21 # 1 | open | https://itmscoaching.herokuapp.com/switch-window?fbclid=IwAR3sjVTRQSHLelERm2a2YkXLkMAARbME8dvuIFHOg0IufS4_67G7MvTrOm0 | 22 @driver.get('https://itmscoaching.herokuapp.com/switch-window?fbclid=IwAR3sjVTRQSHLelERm2a2YkXLkMAARbME8dvuIFHOg0IufS4_67G7MvTrOm0')23 # 2 | setWindowSize | 1042x814 | 24 @driver.manage.resize_to(1042, 814)25 # 3 | click | id=new-tab-button | 26 @vars['window_handles'] = @driver.window_handles27 # 4 | storeWindowHandle | root | 28 @driver.find_element(:id, 'new-tab-button').click29 # 5 | selectWindow | handle=${win1454} | 30 @vars['win1454'] = wait_for_window(2000)31 # 6 | selectWindow | handle=${root} | 32 @vars['root'] = @driver.window_handle33 # 7 | click | id=alert-button | 34 @driver.switch_to.window(@vars['win1454'])35 # 8 | assertAlert | This is a test alert! | 36 @driver.switch_to.window(@vars['root'])37 @driver.find_element(:id, 'alert-button').click38 expect(@driver.switch_to.alert.text).to eq('This is a test alert!')39 end40end...

Full Screen

Full Screen

test_2.rb

Source:test_2.rb Github

copy

Full Screen

...8 end9 it 'test' do10 @driver.get 'https://www.gmail.com'11 binding.pry12 window_handles = @driver.window_handles13 @driver.switch_to.window window_handles[1]14 Selenium::WebDriver.for :chrome15 Selenium::WebDriver.for :chrome16 binding.pry17 end18end19# driver = Selenium::WebDriver.for :chrome20# driver.get 'https://www.gmail.com'21# driver.manage.new_window(:window)22# driver.switch_to.window(driver.window_handles.last)...

Full Screen

Full Screen

window_handles

Using AI Code Generation

copy

Full Screen

1driver.find_element(:name, 'q').send_keys 'Selenium WebDriver'2driver.find_element(:name, 'btnG').click3Selenium::WebDriver::Error::UnknownError: Unable to find element: {"method":"name","selector":"q"}4from UnknownError: Unable to find element: {"method":"name","selector":"q"}5 at Object.checkLegacyResponse (node_modules/selenium-webdriver/lib/error.js:505:15)6 at parseHttpResponse (node_modules/selenium-webdriver/lib/http.js:509:13)7 at Executor.execute (node_modules/selenium-webdriver/lib/http.js:435:26)8 at process._tickCallback (internal/process/next_tick.js:68:7)9driver.find_element(:name, 'q').send_keys 'Selenium WebDriver'10driver.find_element(:name, 'btnG').click

Full Screen

Full Screen

window_handles

Using AI Code Generation

copy

Full Screen

1driver.find_element(:link_text, 'Gmail').click2driver.find_element(:link_text, 'Images').click3driver.find_element(:link_text, 'Gmail').click4driver.find_element(:link_text, 'Gmail').click5driver.find_element(:link_text, 'Images').click6driver.find_element(:link_text, 'Gmail').click7driver.find_element(:link_text, 'Gmail').click8driver.find_element(:link_text, 'Images').click9driver.find_element(:link_text, 'Gmail').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