How do you set the browser inner window/viewport s

2019-06-24 06:39发布

问题:

If I call the function:

browser.driver.manage().window().setSize(1000, 1000);

It sets my window size to 1000x1000 and my inner window/viewport size to 990x918. By inner window size, I mean the portion of the window that actually contains the content, not including window borders or tabs, for example. In this case, I have a 5px border on each side, and then 82px worth of url and tab bars that I would like to account for.

I'd like to set the inner window size so that I dont need to potentially account specifically for the machine running the tests, should it happen to have an extra toolbar for example.

Is there a protractor command for setting the size of the actual inner, content-filled portion of the window?


As based on the answer below, I added this to the onPrepare section of my conf:

protractor.setViewportSize = function(width, height){
    const JS_GET_PADDING = "return {"
       + "w: window.outerWidth - window.innerWidth,"
       + "h: window.outerHeight - window.innerHeight };";

     browser.executeScript(JS_GET_PADDING).then(function(pad){
       browser.manage().window().setSize(width + pad.w, height + pad.h);
     });
};

And in the test, I call something like:

protactor.setViewportSize(1440, 1000);

回答1:

I don't think that there's any build-in method to resize the viewport to a given size. However it can be done by setting an outter size that will match the targeted inner size:

var webdriver = require('./node_modules/protractor/node_modules/selenium-webdriver');

// extension method to set the inner size
webdriver.WebDriver.prototype.setViewportSize = function(width, height){
  const JS_GET_PADDING = "return {"
    + "w: window.outerWidth - window.innerWidth,"
    + "h: window.outerHeight - window.innerHeight };";

  var self = this;
  self.executeScript(JS_GET_PADDING).then(function(pad){
    self.manage().window().setSize(width + pad.w, height + pad.h);
  });
};

// start the browser
var driver = new webdriver.Builder().withCapabilities({browserName: 'firefox'}).build();

// set the window inner size to 800 x 600
driver.setViewportSize(800, 600);

// quit
driver.sleep(5000);
driver.quit();