DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Selenium vs Cypress: Does Cypress Replace Selenium?
  • Playwright: Test Automation You Must Know
  • Migrating from React Router v5 to v6: A Comprehensive Guide
  • AI-Driven Self-Healing Tests With Playwright, Cucumber, and JS

Trending

  • How to Convert XLS to XLSX in Java
  • AI-Driven Test Automation Techniques for Multimodal Systems
  • Contextual AI Integration for Agile Product Teams
  • Building Custom Tools With Model Context Protocol
  1. DZone
  2. Coding
  3. JavaScript
  4. WebdriverIO Tutorial: Browser Commands for Selenium Testing

WebdriverIO Tutorial: Browser Commands for Selenium Testing

See how to perform various actions within a browser through WebdriverIO browser commands for Selenium test automation.

By 
Rahul Jain user avatar
Rahul Jain
·
Jun. 05, 20 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
13.2K Views

Join the DZone community and get the full member experience.

Join For Free

WebdriverIO is a very well known End to End JavaScript testing framework for automation testing. It is based in Node.js and can further help you automate user activities on a browser with the help of WebdriverIO browser commands. WebDriverIO browser commands are used to directly perform certain actions on the browser. There are a few examples: Opening browser, Finding element, Navigating forward, back, Refreshing the page also Close the browser.

In Selenium, a driver object is created to interact with the browser. However, in WebDriverIO you can set up a WebDriverIO test runner to directly use a globally initialized ‘driver' or ‘browser’ object. In this WebDriverIO tutorial, I will cover the ‘browser’ object and how to use them. While running the script, the browser session gets automatically initialized and closed. You don't have to create objects separately in WebDriverIO.

In our previous WebriverIO tutorial I had covered more about the basics of WebdriverIO and how you can run WedbdriverIO scripts. In this WebdriverIO tutorial, I will focus on the major challenges you might face while working on your Selenium Automation Scripts in WebDriverIO. I will further give a solution to all these issues with respective WebdriverIO commands for Selenium testing in detail in this WebDriverIO tutorial along with examples. 

How to Handle Browser Windows With WebdriverIO Commands?

In this WebdriverIO tutorial, I’ll now discuss some major issues you might encounter while handing browser windows to run your Selenium test Automation Scripts.  This includes finding your browser window size, it’s a specification and other action you can perform on these browsers.

How to Find Your Window Size With WebdriverIO?

This command returns the current window size. Basically, getWindowSize() will help when you want to run an automation script on a particular browser size. Output of this command is in format  { height: 798, width: 1200, x: 22, y: 45 }

Syntax:

 browser.getWindowSize() 

Example: Print the current browser window size on console

JavaScript
 




x


 
1

          
2
describe("Browser Commands ", function() {
3
       it("getWindowSize example ", function() {
4
               browser.url("https://www.lambdatest.com/");
5
               console.log(browser.getWindowSize());
6
       });
7
  });
8

          


How to Specify Your Window Size With WebdriverIO?

Sometimes, we want to set a specific height and width of the browser. In such cases, setWindowSize will help you. It takes two parameters, height and width as an Integer. 

Syntax:

 browser.setWindowSize(width, height) 

Example: Open the current browser and change the width and height of that browser.

JavaScript
 




xxxxxxxxxx
1
10


 
1

          
2
describe("Browser Commands ", function() {
3
       it("setWindowSize example ", function() {
4
               browser.url("https://www.lambdatest.com/");
5
               browser.setWindowSize(100, 300);
6
               browser.pause(5000);
7
               console.log(browser.getWindowSize());
8
       });
9
   });
10

          


How to Open a New Window With WebdriverIO?

newWindow command is used when you want to open a new url on a new browser window. Other parameters included are windoname and window features. You can use them to set the name of the window along with its size, position etc respectively.

Syntax:

 browser.newWindow(url, NewWindowName, NewWindowsFeature) 

Example: Open two URL  https://www.lambdatest.com/   and  https://www.google.com/  then search particular text on the newly open window.

JavaScript
 




xxxxxxxxxx
1
20


 
1

          
2
describe("Browser Commands ", function() {
3
       it("newWindow example ", function() {
4
               browser.url("https://www.lambdatest.com/");
5

          
6
               browser.newWindow(
7
                   "https://www.google.com/",
8
                   "Google Window",                            
9
                   "width=800,height=700,resizable,scrollbars=yes,status=1"
10
               );
11
               browser.pause(5000);
12
               console.log(browser.getTitle());
13
               // opening Google and writing text on newly opened window
14
               $(".//input[@name='q']").setValue("lambdatest.com");
15
               browser.pause(5000);
16
       });
17
});
18

          
19

          
20

          


How to Close Browser Window With WebdriverIO?

closeWindow command is very similar to the newWindow command. closeWindow command helps to close the browser between the script execution. Remember, closeWindow will not close the main browser.  If the browser context is not handled and found no parent/main context then It will close all browsers.

Syntax

 browser.closeWindow() 

Example: Open url https://www.lambdatest.com/  and https://www.google.com/ then close all opened browsers.

JavaScript
 




xxxxxxxxxx
1
18


 
1

          
2
describe("Browser Commands ", function() {
3
       it("closeWindow  example ", function() {
4
               browser.url("https://www.lambdatest.com/");
5

          
6
               browser.newWindow(
7
                       "https://www.google.com/",
8
                       "Google Window",
9
                       "width=800,height=700,resizable,scrollbars=yes,status=1"
10
               );
11
               browser.pause(5000);
12
               console.log(browser.getTitle()); // print google title
13
               browser.pause(5000);
14
               browser.closeWindow();
15
              
16
       });
17
});
18

          


How to Switch Browser Window With WebdriverIO?

 switchWindow()  command helps in automatically switching to a specific browser/tab. It takes a string parameter as URL or browser title name. 

Syntax:

 browser.switchWindow(urlOrTitleOfWindow) 

Example: Open two URLs https://www.lambdatest.com/  and https://www.google.com/ then print the first URL title and then second browser title.

JavaScript
 




xxxxxxxxxx
1
24


 
1

          
2
describe("Browser Commands ", function() {
3
       it("swtichWindow  example ", function() {
4
               browser.url("https://www.lambdatest.com/");
5

          
6
               browser.newWindow(
7
                       "https://www.google.com/",
8
                       "Google Window",
9
                       "width=800,height=700,resizable,scrollbars=yes,status=1"
10
               );
11
               browser.pause(5000);
12
               console.log(browser.getTitle()); // print google title
13

          
14
               browser.switchWindow("https://www.lambdatest.com/");
15
               browser.pause(5000);
16
               console.log(browser.getTitle()); // print landatest title
17

          
18
               $("=Automation").click();
19

          
20
               browser.switchWindow("Google");
21
               console.log(browser.getTitle()); // print google title
22
       });
23
  });
24

          


How to Maximize Browser Window With WebdriverIO?

 maximizeWindow  command helps the browser to maximize the browser window for automated browser testing.

Syntax:

 browser.maximizeWindow() 

Example:

JavaScript
 




xxxxxxxxxx
1
10


 
1

          
2
describe("Browser Commands ", function() {
3
   it("maximize Command", function() {
4
       browser.url("https://www.lambdatest.com/");
5

          
6
       browser.maximizeWindow();
7
       $("=Automation").click();
8
   });
9
});
10

          


How to Minimize a Browser Window With WebdriverIO?

minimize window helps users to minimize the window during the execution. Note that even the browser window is minimized, still, script execution continues without any error. The below example shows that even if the browser minimized, the script is successfully clicked on the Automation link. 

Syntax: 

 browser.minimizeWindow() 

Example: Click on the Automation link of LambdaTest URL after minimizing the browser window. 

JavaScript
 




xxxxxxxxxx
1
14


 
1

          
2
describe("Browser Commands ", function() {
3
   it("minimize Command", function() {
4
       browser.url("https://www.lambdatest.com/");
5

          
6
       browser.maximizeWindow();
7
       browser.pause(5000);
8

          
9
       browser.minimizeWindow();
10

          
11
       $("=Automation").click();
12
   });
13
});
14

          


How to Go Fullscreen on a Browser With WebdriverIO?

With the  fullscreenWindow  command, the browser can be seen on the full screen. It hides the browser Menu bar and bookmarks if visible. 

Syntax:

 browser.fullscreenWindow() 

Example: Open url in fullscreen mode and click on Automation.

JavaScript
 




xxxxxxxxxx
1
10


 
1

          
2
describe("Browser Commands ", function() {
3
   it("fullscreenWindow Command", function() {
4
       browser.url("https://www.lambdatest.com/");
5
       browser.pause(5000);
6
       browser.fullscreenWindow();
7
       $("=Automation").click();
8
   });
9
});
10

          


How to Navigate Browser Windows With WebdriverIO Browser Commands?

While performing Selenium test automation, you’d have to navigate to different URLs, including the one you’ve used before the current URL. Here in this WebdriverIO tutorial, I’ll further address the issues you might face.

How to Open a New URL in the Same Window With WebdriverIO?

 navigateTo  command helps you to open a new URL on the same open browser.

Syntax:  browser.navigateTo(url) 

Example: Open the URL  https://www.lambdatest.com/  and then navigate to new URL  https://www.google.com/  on the same page. 

JavaScript
 




xxxxxxxxxx
1
10


 
1

          
2
describe("Browser Commands ", function() {
3
       it("NavigateTo Command", function() {
4
               browser.url("https://www.lambdatest.com/");
5
               const title = browser.getTitle();
6
               console.log(title);
7
               browser.navigateTo("https://www.google.com/");                
8
       });
9
});
10

          


How to Navigate to Previous Page Using WebdriverIO?

back() command helps in automating the back button for any page. By using this command you can go back to the previous page of the open browser. 

Syntax: browser.back() 

Example: Open the URL  https://www.lambdatest.com/  and then navigate to new URL  https://www.google.com/  on the same page and go back again to the old URL. 

JavaScript
 




xxxxxxxxxx
1
14


 
1

          
2
describe("Browser Commands ", function() {
3
       it("Back() Command", function() {
4
               browser.url("https://www.lambdatest.com/");
5
               const title = browser.getTitle();
6
               console.log(title);
7

          
8
               browser.navigateTo("https://www.google.com/");
9
               browser.back();
10
               const title = browser.getTitle();
11
               console.log(title);
12
       });  
13
});
14

          


How to Navigate to Forwarding URL Using WebdriverIO?

Forward helps to navigate from the current web URL to the forward URL. This will be read from the browser history. If history URL is not found then it will use the current URL only. To use this URL, you are required to use back() in order to create navigation history.

Syntax: browser.forward();  

Example: Open the URL  https://www.lambdatest.com/  and then navigate to new URL  https://www.google.com/  on the same page, go back and forward the URL.

JavaScript
 




xxxxxxxxxx
1
13


 
1

          
2
describe("Browser Commands ", function() {
3
       it("forward() Command", function() {
4
               browser.url("https://www.lambdatest.com/");
5
               const title = browser.getTitle();
6
               console.log(title);
7
               browser.navigateTo("https://www.google.com/");
8
               browser.back();
9
               browser.forword();
10
               console.log(browser.getTitle());
11
       });
12
});
13

          


How to Manage Page Load With WebdriverIO Browser Commands?

Moving ahead with this WebdriverIO tutorial, I’ll dwell on how you can pause execution for a given time, refreshing your webpage, and how to load your page after a certain timeout.

How to Pause Page Load With WebdriverIO?

Pause() method is used to pause execution for a given time. The parameter is passed in milliseconds. Avoid using this constant pause. This will increase execution time as we are giving a specific time duration. It is similar to Thread.sleep()

Syntax:  browser.pause(milliseconds)  

Example: Open  https://www.lambdatest.com/  and wait for 5000 milliseconds before clicking on Automation link

JavaScript
 




xxxxxxxxxx
1


 
1
describe("Browser Commands ", function() {
2
       it("Pause example ", function() {
3
               browser.url("https://www.lambdatest.com/");
4
               browser.pause(5000);
5
               $("=Automation").click();
6
       });
7
});
8

          


How to Refresh Your Page With WebdriverIO?

Refresh is a very less frequently used command in automation. WebDriverIO provides this command to reload your current browser.

Syntax:  browser.refresh()  

Example: Open Url and reload again the same URL. 

JavaScript
 




xxxxxxxxxx
1


 
1

          
2
describe("Browser Commands ", function() {
3
       it("refresh() Command", function() {
4
               browser.url("https://www.lambdatest.com/");
5
               browser.refresh();
6
               console.log(browser.getTitle());
7
       });
8
});
9

          


How to Handle Timeout With WebdriverIO?

WebDriverIO provides a timeout command to handle script injection execution, page load time on the element during the current session. All values for the time is in milliseconds. 

Implicit: Implicit wait waits for a given time and if the element is found in this duration then WebDriverIO performs an operation or else throws element not found error. The benefit of using implicit wait in Selenium is that it is applicable for all the web elements specified in the Selenium test automation script till the time the WebDriver instance (or IWebDriver object) is alive.

pageLoad: Execution waits for the page to completely load all resources. 

Script: Script injection and execution should complete before a given timeout reaches to the end. 

Timeout commands should be written in the hooks provided by WebDriverIO so that you do not have to write every time a JavaScript file is created. 

Syntax: browser.setTimeout({ timeouts.implicit, timeouts.pageLoad, timeouts.script}) 

Example: Open a URL and click on the element.

JavaScript
 




xxxxxxxxxx
1


 
1

          
2
describe("Browser Commands ", function() {
3
   it("timeout Command", function() {
4
       browser.url("https://www.lambdatest.com/");
5
       browser.setTimeout({ implicit: 10000, pageLoad: 10000, script: 5000 });
6
       $("=Automationsssss").click(); // Wrong element selector and throw error after 10000 millisecond
7
   });
8
});
9

          


Note: Above example gives an error that “Automationsssss” can not be found as we are giving you an example of the implicit wait. 

Other Important WebdriverIO Browser Commands

Here is some other important browse.r commands in WebdriverIO which can be used for your Selenium Test Automation Scripts. Here are some Selenium test automation tips.

How to Open URL Using Webdriver Command

One of the most basic and frequently used WebDriverIO browser commands is URL(). This command helps users to open the URL on the configured browser. Parameter ‘String URL’ is optional and if the parameter is not passed then it will pick ‘baseUrl’ from ‘wdio.conf.js’ file 

Syntax: browser.url(String url) 

Example: Open  https://www.lambdatest.com/  URL in the browser.

JavaScript
 




xxxxxxxxxx
1


 
1

          
2
describe("Browser Commands ", function() {
3
       it("Open URL", function() {
4
               browser.url("https://www.lambdatest.com/");
5
       });
6
});
7

          


How to Capture Title With WebdriverIO?

getTitle() is used to capture the value of an open browser title. The return value is trimmed and in case there is no browser title it’ll return a null value. 

Syntax: browser.getTitle()  

Example: Open  https://www.lambdatest.com/  URL and print browser title.

JavaScript
 




xxxxxxxxxx
1


 
1

          
2
describe("Browser Commands ", function() {
3
       it("Open URL and print browser Title", function() {
4
               browser.url("https://www.lambdatest.com/");
5
               const title = browser.getTitle();
6
               console.log(title);
7
       });
8
});


How to Find Elements With WebdriverIO?

You might be familiar with  findElemnt()  method in Java. WebDriverIO has a similar method, ‘$()’. It will automatically identify the locator and find the element according to the locator. Since it is a global variable you can directly write $(String selector). 

The $() method will return only a single web element. In case, you want to store an element then store that element in a const variable and perform an action. You can also use $() as a chain selector, i.e. $(selector).$(selector).$(selector), advantage of using a chain selector is that you can go inside the DOM and select a particular element.  

Syntax: browser.$(String selector) 

Or 

 $(String selector )  

Example: Open  https://www.lambdatest.com/  and Click on Automation, Pricing and again Automation Header link.

JavaScript
 




xxxxxxxxxx
1
19


 
1

          
2
describe("Browser Commands ", function() {
3
       it("Open URL and print browser Title and ClickOn Header Link", function() {
4
               browser.url("https://www.lambdatest.com/");
5
               const title = browser.getTitle();
6
               console.log(title);
7
               browser.$("=Automation").click();
8

          
9
               // Or
10
               $("=Pricing").click(); // Without writing 'browser' object
11

          
12
              // Store element in elem variable using const 
13
              const elem = $("=Automation");
14
              elem.click();
15

          
16

          
17
       });
18
});


How to Find Multiple Elements With WebdriverIO?

$$() is similar to the $() method, however $() returns a single web element and $$() method will return an array of elements. $$() is also defined globally so you can directly write $$() without using the ‘browser’ object and it can also be used as a support chain selector. 

Syntax: browser.$$(String selector)  

Or 

 $$(String selector ) 

Example: Read all header links of  https://www.lambdatest.com/  and print their text.

JavaScript
 




xxxxxxxxxx
1
12


 
1
describe("Browser Commands ", function() {
2
           it("$$ example ", function() {
3
               browser.url("https://www.lambdatest.com/");
4

          
5
               const lstHeaderLinks = $$(".//*[@class='navbar-nav']/li");
6

          
7
               lstHeaderLinks.forEach(element => {
8
                       console.log(element.getText());
9
               });
10
       });
11
});


How to Manage Your Browser Cookies With WebdriverIO?

deleteCookie WebDriverIO command is a very useful browser command. It helps users to delete stored cookies from the browser session. This will help users to delete specific cookies provided in the parameter. 

To know the name of the cookies, you can use the  browser.getAllCookies()  and print a console log to get more information about cookie names. 

If you want to delete all cookies related to the opened browser, then use  getAllCookies()  WebDriverIO command.

Syntax: browser.deleteCookie(nameOftheCookie)  

Example: Open URL and read all stored cookies and then delete particular cookies. 

JavaScript
 




xxxxxxxxxx
1
11


 
1

          
2
describe("Browser Commands ", function() {
3
       it("Cookies Command", function() {
4
               browser.url("https://www.lambdatest.com/");
5
               console.log(browser.getTitle());
6
               console.log(browser.getAllCookies());
7
               browser.deleteCookie("utm_medium");
8
               browser.deleteAllCookies();
9
       });
10
  });


There are many more commands which are provided by WebDriverIO javascript and we will further explore them in another WebDriverIO tutorial.

That’s All Folks

In this WebDriverIO tutorial, I explored a few very basic and frequently used JavaScript browser commands for Selenium Grid. These WebDriverIO commands help users configure the script based on browser configuration. I hope this helped you!

You can even scale your automated browser testing by using WebdriverIo along with a Selenium Grid to perform parallel testing. Although maintaining your own Selenium Grid can be quite exhaustive you can choose Cloud Selenium Grids to scale your efforts. In order to know more about this topic, you can read our previous WebDriverIO tutorial.

Happy testing!

Command (computing) JavaScript Syntax (programming languages) Element Test automation Execution (computing)

Published at DZone with permission of Rahul Jain. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Selenium vs Cypress: Does Cypress Replace Selenium?
  • Playwright: Test Automation You Must Know
  • Migrating from React Router v5 to v6: A Comprehensive Guide
  • AI-Driven Self-Healing Tests With Playwright, Cucumber, and JS

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!