How can I set the browser window size when using `google-chrome --headless`?

后端 未结 3 1636
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-08 06:49

I tried setting the browser size on Chrome --headless by using Selenium WebDriver commands.

I get this WebDriver error:

      - Failed: un         


        
相关标签:
3条回答
  • 2020-12-08 07:03

    I had a problem with screen resolution when running on Jenkins (which forces headless mode). The solution was very simple: set headless mode to true explicitly. For some reason, not doing this explicitly caused my screen to "shrink" causing all kinds of "element intercept click" issues. Because I was taking screenshots during failures, I noticed the resolution (size) was not right. Once I did this, the problem went away; confirmed by screenshots taken during failures.

    To avoid conflicts with local configurations, I moved the value of this flag into a configuration file that was then added to our .gitignore file to prevent accidental overwrites.

    If you are like me, where none of these commonly solutions worked out, make sure you explicitly set this value:

    ChromeOptions options = new ChromeOptions();
    ...
    String headlessMode = readProperty("headless_mode"); // Get value from some prop file (my own implementation)
    options.setHeadless(Boolean.valueOf(headlessMode));
    ...
    driver = new ChromeDriver(options);
    

    If you don't want (or need) this separation, simply set the value to true in the setHeadless method call.

    0 讨论(0)
  • 2020-12-08 07:15

    I found it. Simply pass the --window-size command line argument to Google Chrome, for example --window-size=1920,1080.

    In a Protractor configuration this would look like this:

    capabilities: {
        browserName: 'chrome',
        chromeOptions: {
            args: ['headless', 'window-size=1920,1080']
        }
    }
    

    The cool thing is that the windows size is not limited to the current display. It is truly headless, meaning it can be as large as needed for the tests.

    Java code:

    options.addArguments("window-size=1920,1080");
    

    I expand a bit more on this in Headless protractor not sharding tests.

    0 讨论(0)
  • 2020-12-08 07:26

    Use the built-in Selenium function:

        aDriver.manage().window().setSize(new Dimension(width, height));
    

    It works like a champ. I've used it for Firefox, Chrome (even headless), and Edge.

    0 讨论(0)
提交回复
热议问题