How to set default browser window size in Protractor/WebdriverJS
Asked Answered
H

9

110

For some reason when I run my tests at work the browser is maximized, but when I run them at home it only opens a browser window of about 50% width. This causes some discrepancies with scrolling down, etc., so I'd ideally like to have it open a browser window of the same size on every machine the tests are run on. What's the best way to do this?

(I've found some answers for other languages, but I haven't been able to adapt them to JavaScript)

Adding

browser.executeScript('window.moveTo(0,0);' +
    'window.resizeTo(screen.width, screen.height);');

does nothing (apparently window.moveTo and window.resizeTo are not supported by Google Chrome).

Haddad answered 16/11, 2013 at 20:35 Comment(8)
I don't have an answer for you at this time, but I can tell you that window.moveTo and window.scrollTo are definitely supported by Chrome.Illa
scrollTo works. But the others don't, at least not from what I can tell. Try typing it in the console...does nothing.Haddad
At the risk of getting off-topic, here is a fiddle that illustrates window.moveTo and window.resizeTo. It works fine for me in Chrome. I don't know that you can resize the current window from the console in Chrome, but the fact that the resizeTo method is available there indicates Chrome supports it.Illa
Ok, seems to be working for new windows that the browser opens with JS. But does not work with the current window, which is what I need.Haddad
I don't have an answer either, but I would certainly question whether you're doing things right if your test is dependent on screen size or whether the browser is maximised - perhaps it makes sense to refactor your test to not have that dependency?Lithea
My test is for whether or not things work and are visible in different responsive configurations, so I need to be able to control the window size for each test.Haddad
start chrome browser with option --window-size=360,640 can helpCoatbridge
The docs for configuring Protractor sites.google.com/a/chromium.org/chromedriver/capabilities suggest capabilities.chromeOptions.args: "start-maximized" in the config file (see also peter.sh/experiments/chromium-command-line-switches )Milan
C
200

You can set the default browser size by running:

var width = 800;
var height = 600;
browser.driver.manage().window().setSize(width, height);

To maximize the browser window, run:

browser.driver.manage().window().maximize();

To set the position, run:

var x = 150;
var y = 100;
browser.driver.manage().window().setPosition(x, y);

If you get an error:

WebDriverError: unknown error: operation is unsupported with remote debugging

Operation not supported when using remote debugging Some WebDriver commands (e.g. resizing the browser window) require a Chrome extension to be loaded into the browser. ChromeDriver normally loads this "automation extension" every time it launches a new Chrome session.

However ChromeDriver can be instructed to connect to an existing Chrome session instead of launching a new one. This is done using 'debuggerAddress' in the Capabilities (aka ChromeOptions) object. Since the automation extension is only loaded at startup, there are some commands that ChromeDriver does not support when working with existing sessions through remote debugging.

If you see the error "operation not supported when using remote debugging", try rewriting the test so that it launches a new Chrome session. This can be done by removing 'debuggerAddress' from the Capabilities object.

Source: Operation not supported when using remote debugging

Conjoined answered 25/11, 2013 at 16:54 Comment(12)
It's also possible to maximise the browser to the full screen size using browser.driver.manage().window().maximize();Docia
@BenSmith: I mentioned that since my initial answer :)Vampire
If you want to have the same resolution for all of your tests, you can call the above in your protractor.conf.js file's onPrepare function.Potamic
@BenSmith not sure why, but browser.driver.manage().window().maximize(); doesn't actually maximize the window for me. I just get a slightly larger window. I just end up specifying a width and height with the setSize() methodFaraday
.maximize doesn't seem to work when you go headless I suppose. I had to specify explicitly the size of the windowPilliwinks
@AlexandrosSpyropoulos : it should work but you have to make sure that you're not running xvfb in some silly resolution. For e.g. by default it's 640x480.Howling
How would you do to use the same sizes when forking? Do I have to set the size manually then again?Loach
@Loach what do you mean by forking?Vampire
@RăzvanPanda Oh sorry, I was refering to a Protractor (Angular testing framework) action. You can create new browser windows in Protractor by forking a new driver instance. It would be nice if you could specify some standard dimensions to always open new browser windows in.Loach
That gives me WebDriverError: unknown error: operation is unsupported with remote debuggingMilan
@LeeGee Updated answer.Vampire
Something seems to be missing after "If you get an error".Boraginaceous
T
42

You can also use your config.js to set window size:

// config.js
specs: [
    ...
],
capabilities: {
    browserName: 'chrome',
    chromeOptions: {
        args: ['--window-size=800,600'] // THIS!
    }
}
// ....
Titicaca answered 27/10, 2016 at 12:17 Comment(3)
you need remove double dash : args: ['window-size=800,600']Carbide
This works as expected for me WITH the double dash as shown in the answer.Micelle
This also sets the browser sizes when running e2e scripts with the '--headless' args. Which is handy if menu gets shifted to mobile view.Vulture
P
28

If the preferred method:

browser.driver.manage().window().maximize();

doesn't work for you (for example running Protractor tests in Xvfb), then you can also maximize window this way (protractor.conf.js):

onPrepare: function() {
    setTimeout(function() {
        browser.driver.executeScript(function() {
            return {
                width: window.screen.availWidth,
                height: window.screen.availHeight
            };
        }).then(function(result) {
            browser.driver.manage().window().setSize(result.width, result.height);
        });
    });
},

TypeScript version:

import {Config, browser} from "protractor";

export let config: Config = {
    ...
    onPrepare: () => {
        setTimeout(() => {
            browser.driver.executeScript<[number, number]>(() => {
                return [
                    window.screen.availWidth,
                    window.screen.availHeight
                ];
            }).then((result: [number, number]) => {
                browser.driver.manage().window().setSize(result[0], result[1]);
            });
        });
    }
};
Pennsylvania answered 24/9, 2015 at 16:18 Comment(4)
best ideea with auto get max resolution, but you forgot setPosition(0, 0) so it will be exactly over the screenPolymer
Hm, my browser already starts at position 0-0. But good point if someone need it.Pennsylvania
mine starts at... 50,50 or something.. just saying :)Polymer
it may depend on the OS, here it's Windows 8.1 run inside Hyper-VPolymer
T
17

I simply added the code below in my protractor.conf.js file and it did work fine.

onPrepare: function() {
    var width = 1600;
    var height = 1200;
    browser.driver.manage().window().setSize(width, height);
},

What purpose does the setTimeout and executeScript serve in your answer? I struggle to find best practices in the protractor documentation...

To my mind, using directly maximize() is a bad idea and should not be the preferred method, since it would not set the same size on every machine where the tests are executed and could break responsive behaviours.

Traditor answered 31/3, 2016 at 16:35 Comment(0)
R
5

In Protractor.conf.js file add following configuration

capabilities: {
    'browserName': 'chrome',
    chromeOptions: {
      args: [
               'start-maximized'
            ]
    }
}
Rheometer answered 5/2, 2019 at 5:58 Comment(0)
P
5

In Selenium 4 (Protractor 6), setRect replaces setSize and setPosition

For example,

browser.driver.manage().window().setRect({height: 600, width: 800});
Prader answered 3/4, 2019 at 15:1 Comment(0)
P
0

Modify your config.js file as per below.

onPrepare: function () {
    browser.driver.manage().window().setSize(1280, 1024); // Width, height
},
capabilities: {
    browserName: 'chrome',
    chromeOptions: {
        args: [ "--start-maximized" ] // To start the browser as maximixed
    }
},
Pupa answered 22/12, 2019 at 14:37 Comment(0)
T
0

if you want to go with async/await

You can maximize the window globally (once the browser started) like so

// protractor.conf.js

exports.config = {

    async onPrepare() {
        // start browser in specified window size
        await browser.driver
            .manage()
            .window()
            .setSize(1920, 1080);
    },
}

Tacmahack answered 8/2, 2021 at 23:5 Comment(0)
S
-1

Add the below code. This will maximize the browser window.

browser.driver.manage().window().maximize();
Scissure answered 30/7, 2020 at 19:6 Comment(1)
Welcome to stackoverflow. There are already answers that provide this information with much more explanation. Please ensure your answers add something new to the question.Universalist

© 2022 - 2024 — McMap. All rights reserved.