Adjust the dimensions of the viewport in WebdriverJS

Is there a way to launch the Chrome browser with a specific viewport size, like 800x600? I have tried the following code:

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

However, when running window.screen.width in the developer console, it always returns 1440.

I also attempted to use Chrome options with the --window-size=x,y option:

var o = new chrome.Options();
o.addArguments("--window-size=640,480");

driver = new webdriver.Builder().withCapabilities(webdriver.Capabilities.chrome()).setChromeOptions(o).build();

Unfortunately, this code only resizes the window as well.

Can anyone provide me with a Chrome command line option to set the default viewport, similar to how it's done in the Chrome developer console (as shown in the image below), or suggest any other approach using Selenium WebDriverJS?

https://i.sstatic.net/aEJ2G.png

Answer №1

Your provided code is functioning as expected.

However, it's important to note that the code you are using checks the resolution of the screen, not the actual size of the window. The values window.screen.width and window.screen.height correspond to screen dimensions. To obtain the window size, utilize window.innerWidth (and innerHeight). Below is a revised code snippet:

var webdriver = require('selenium-webdriver'),
    driver = null;

function logWindowSize() {
    driver.executeScript(function() {
        return [window.innerWidth, window.innerHeight];
    }).then(console.log);
}

// initialize driver
driver = new webdriver.Builder()
    .withCapabilities(webdriver.Capabilities.chrome())
    .build();
driver.get('http://www.google.com');

// adjust window size
logWindowSize();
driver.manage().window().setSize(640, 480);
logWindowSize();
driver.quit();

The resulting output in the console will be:

[ 945, 1018 ]
[ 640, 375 ]

A discrepancy in height might occur due to tab bar and navigation bar sizes. You can set the window size accurately by adjusting for this difference. Here's an example:

var webdriver = require('selenium-webdriver'),
    driver = null,
    sizeWidth = 640,
    sizeHeight = 480;

// initialize driver
driver = new webdriver.Builder()
    .withCapabilities(webdriver.Capabilities.chrome())
    .build();
driver.get('http://www.google.com');

// adjust window size
driver.manage().window().setSize(sizeWidth, sizeHeight);
driver.executeScript(function() {
    return [window.innerWidth, window.innerHeight];
}).then(function(actualSize) {
    driver.manage().window().setSize(
        2 * sizeWidth - actualSize[0],
        2 * sizeHeight - actualSize[1]
    );
    // display the desired sizes
    driver.executeScript(function() {
        return [window.innerWidth, window.innerHeight];
    }).then(console.log);
});
driver.quit();

Answer №2

The Issue at Hand
There appears to be a strong desire to manipulate the values returned by window.screen.width and window.screen.height. Normally, this is not feasible, unless utilizing Chrome's device mode (along with the accompanying toolbar). So, how about triggering those options?

// initiating inspector and responsive design mode
driver.actions()
    .keyDown(Key.CONTROL)
    .keyDown(Key.SHIFT)
    .sendKeys('im')
    .keyUp(Key.SHIFT)
    .keyUp(Key.CONTROL)
    .perform();

Regrettably, this approach won't succeed in Chrome. As stated in that answer:

The Chrome driver utilizes the Chrome remote debugging protocol for browser communication. This protocol aligns with what the developer console employs as well. Unfortunately, Chrome restricts only one client connection via the protocol at any given time, implying either the developer tools or the driver, but not both concurrently.    — JimEvans

What a letdown. It seems like success can be achieved in this aspect using Firefox, though. Nonetheless, executing actions using Selenium + geckodriver is currently unattainable. Furthermore, there isn't a JavaScript method to activate this mode directly. On a brighter note, we are able to send keys to an element.

A Potential Resolution
The following method has worked effectively for me.

var webdriver = require('selenium-webdriver'),
    firefox = require('selenium-webdriver/firefox'),
    By = webdriver.By,
    Key = webdriver.Key,
    driver = null;

// setting up driver
var profile = new firefox.Profile(),
    devicePreset = [{
        width: 640,
        height: 480,
        key: '640x480',
        name: 'Mobile Device'
    }];
profile.setPreference('devtools.responsiveUI.presets',
                      JSON.stringify(devicePreset));
var opts = new firefox.Options();
opts.setProfile(profile);
var builder = new webdriver.Builder().forBrowser('firefox');
builder.setFirefoxOptions(opts);
driver = builder.build();

driver.get('http://www.google.com');

// activating responsive design mode
driver.findElement(By.css('input[name="q"]'))
    .sendKeys(Key.chord(Key.CONTROL, Key.SHIFT, 'm'));

driver.get('https://www.iplocation.net/find-ip-address');

Please note that I have configured a preference in Firefox indicating the desired screen size for the responsive design mode. Feel free to adjust this according to your preferential screen specifications.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Implementing an Asynchronous Limited Queue in JavaScript/TypeScript with async/await

Trying to grasp the concept of async/await, I am faced with the following code snippet: class AsyncQueue<T> { queue = Array<T>() maxSize = 1 async enqueue(x: T) { if (this.queue.length > this.maxSize) { // B ...

The affix feature in Bootstrap's navbar fails to recognize the height of images

My navbar element affixes prematurely when placed below my header element, making it seem as if the image in the header does not exist. The navbar is meant to affix only when it reaches the top, but currently, it is affixing earlier. The code I used sets ...

In JQuery, an empty string will be returned if it contains the dollar sign character

In the scenario presented here, the value is retrieved accurately with the exception of when it includes a $ symbol at the beginning (e.g. $25.00), in which case it consistently results in an empty string. HTML: <input type="number" class="form-contro ...

Unresolved styles in React component linked to styles.css file

As I dive into creating a registration page in ReactJS, I encounter a frustrating issue with my styles not applying correctly from the styles.css file. Let's take a look at my RegisterPage.jsx component: export default function RegisterPage() { ret ...

Having trouble navigating the page using Selenium in Python?

I have been struggling to successfully scroll down a website using Python/Selenium. The specific website I am trying to scroll down is: Despite several attempts, the farthest I have been able to scroll is halfway down the page. What I actually need is to ...

Troubleshooting problems with opening and closing windows in JavaScript

I'm currently facing an issue with managing browser windows using JavaScript. In my proof of concept application, I have two pages - one for login information (username, password, login button, etc.) and the second page is a management screen. What I ...

Code snippet for fetching JavaScript file using Angular's caching mechanism

Currently in my project, I am utilizing $.getScript to dynamically load specific sections of code. Here's a snippet of how it looks: var mainJs = "/main.js"; $.getScript( mainJs ) .then(function () { console.log("main.js loaded"); }); ...

What could be the reason for the unexpected outcome when checking if display is equal to "none"?

I have a JavaScript function called "display()". I want to hide my navigation menu on click, but it is not working properly - it just blinks. I am looking for a solution that uses only JavaScript and does not involve querySelector. function display() { ...

StopDefault and JSON Placement

We have a form that sends data to an external domain using JSONP to avoid cross-domain limitations. Everything is functioning properly except for preventing the default form submission that triggers a page reload. Below is the HTML code for the form: < ...

How to Handle Tab Navigation on a Mobile Website without Javascript?

My website primarily targets mobile devices, with tabs in the top navigation. Currently, these tabs are hard coded instead of utilizing Javascript. We want to ensure our site is accessible on all mobile devices, including those without Javascript support. ...

Why will the experimental activation of React concurrent features in Nextjs 12 disable API routes?

I just upgraded to Next.js version 12 and set up some API routes (e.g. "/api/products"). These routes were functioning properly, but when I enabled concurrentFeatures: true in my next.config.ts, the API routes stopped working. The console display ...

Click on the print icon in the modal window

I have been working on a receipt generator for a client. The client can add payment receipts using the "Add" button, and upon submission, they have the option to convert it to PDF or print it. However, there seems to be an issue with printing as the text f ...

Is there a way to insert a secured page right before accessing the dashboard?

I am trying to create a locked page that will display a message when users access the web app from a mobile device and load a mobile layout page displaying a message like mobile is not supported. I was considering using document.addEventListener('DOMC ...

Is there a way for me to retrieve the locator value of a webelement?

How can I retrieve the selector value used in a selenium webelement in javascript? Let's say I have the following object: var el = browser.driver.findElement(by.id('testEl')); I want to extract the text 'testEl' from this object ...

JavaScript for Loading and Moving Ads in IE8

On my website at , I have placed my AdSense ads at the top of the page. However, I encountered an issue with Internet Explorer 8 where the Javascript code I used to move the ads to a different position on the page doesn't seem to work: <!-- POSI ...

How to simulate loadStripe behavior with Cypress stub?

I am struggling to correctly stub out Stripe from my tests CartCheckoutButton.ts import React from 'react' import { loadStripe } from '@stripe/stripe-js' import useCart from '~/state/CartContext' import styles from '. ...

Setting a fixed data value within a div for subsequent retrieval through a function

I found a helpful example that demonstrates how to convert numbers into words. You can check it out here. The function for converting numbers into words is implemented in the following HTML code: <input type="text" name="number" placeholder="Number OR ...

In a VueJS project, access an xlsx file stored in the public directory by reading its contents

My current challenge involves trying to extract a quiz template from an xlsx file in order to create the quiz within it. Unfortunately, storing the xlsx file as json in a database is not a feasible solution for me at this time. I experimented with using ...

Steps for selecting the text "Thank you for Registering" using Xpath in Selenium

I attempted to retrieve the text "Thank you for signing up" using the following Xpath: Xpath : By.xpath("//span[@class='lblMessageSignup']") or "//div[@class='SignupContent']/span" and utilized the gettext method to extract the text ...

Step-by-step guide for executing test methods sequentially using JUnit

Currently utilizing JUnit and Selenium Webdriver for my testing. My objective is to have the test methods run in the exact order as they are written in my code, like so: @Test public void registerUserTest(){ // code } @Test public void welcomeNewUser ...