Method: Capybara::Session#switch_to_window

Defined in:
lib/capybara/session.rb

#switch_to_window(&block) ⇒ Capybara::Window #switch_to_window(window) ⇒ Capybara::Window

Returns window that has been switched to

Overloads:

  • #switch_to_window(&block) ⇒ Capybara::Window

    Switches to the first window for which given block returns a value other than false or nil. If window that matches block can't be found, the window will be switched back and `WindowError` will be raised.

    Examples:

    window = switch_to_window { title == 'Page title' }

    Raises:

  • #switch_to_window(window) ⇒ Capybara::Window

    Parameters:

    Raises:

Returns:

Raises:

  • (Capybara::ScopeError)

    if this method is invoked inside `within`, `within_frame` or `within_window` methods

  • (ArgumentError)

    if both or neither arguments were provided



425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
# File 'lib/capybara/session.rb', line 425

def switch_to_window(window = nil, options= {})
  options, window = window, nil if window.is_a? Hash

  block_given = block_given?
  if window && block_given
    raise ArgumentError, "`switch_to_window` can take either a block or a window, not both"
  elsif !window && !block_given
    raise ArgumentError, "`switch_to_window`: either window or block should be provided"
  elsif scopes.size > 1
    raise Capybara::ScopeError, "`switch_to_window` is not supposed to be invoked from "\
                                "`within`'s, `within_frame`'s' or `within_window`'s' block."
  end

  if window
    driver.switch_to_window(window.handle)
    window
  else
    wait_time = Capybara::Queries::BaseQuery.wait(options)
    document.synchronize(wait_time, errors: [Capybara::WindowError]) do
      original_window_handle = driver.current_window_handle
      begin
        driver.window_handles.each do |handle|
          driver.switch_to_window handle
          if yield
            return Window.new(self, handle)
          end
        end
      rescue => e
        driver.switch_to_window(original_window_handle)
        raise e
      else
        driver.switch_to_window(original_window_handle)
        raise Capybara::WindowError, "Could not find a window matching block/lambda"
      end
    end
  end
end