5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Capybaraでブラウザのウィンドウサイズをモニタに合わせて自動最大化する方法

Last updated at Posted at 2016-06-26

SeleniumにはWindowを最大化するAPIとしてCapybara.page.driver.browser.manage.window.maximizeが存在していますが、問題点としてChromeとFirefoxで最大化時の幅が異なるという問題点があります。Chromeはページが十分に見える幅まで最大化するのに対して、Firefoxは画面いっぱいに最大化します。

従って、クロスブラウザでウィンドウ幅を均一にするには、同じwindowオブジェクトに生えているresize_toメソッドを使うことになります。このメソッドはresize_to(幅, 高さ)を数値で指定するので、ここに画面の大きさを入れてあげればいいわけです。

以下のコードはRSpecで画面幅を最大1024とし、それよりモニタが小さい場合、モニタの幅に合わせるようにしたコードです。モニタの幅や高さの算出はJavaScriptをブラウザに実行させています。

spec_helper.rb
require 'capybara'

RSpec.configure do |config|
  max_window_width = 1024
  config.before(:all) do
    screen_height = Capybara.page.execute_script("return screen.height;")
    screen_width = Capybara.page.execute_script("return screen.width;")
    screen_width = [screen_width, max_window_width].min
    Capybara.page.driver.browser.manage.window.move_to(0, 0)
    Capybara.page.driver.browser.manage.window.resize_to(screen_width, screen_height)
  end
end

最大幅を設定している理由は、最近のモニタは幅が1640だったりとウェブページとしては広すぎることもあるため、ウェブページとして広すぎない幅にするために設定しています。

5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?