Make Selenium Easy

How To Get Current URL Using JavaScript In Selenium Java?

Introduction

Selenium WebDriver with Java already provides a method named getCurrentUrl() to get the currently loaded URL in a browser and I don’t see any scenario in which this method has not worked as expected. But sometimes in interviews, some tricky questions are asked. “How to get current URL of browser without using getCurrentUrl() method?” is one of them.

Did you know that I have started a YouTube channel as well and I need your support to make it successful. Please do watch content then comment, like, share, and obviously subscribe.

Using JavaScript to get the current URL

We can use the JavaScript command here to get the current URL of a browser. Since JavaScript is enabled for all browsers nowadays to make web pages dynamic we can easily execute JavaScript commands.

You can run the JavaScript command in a browser. Perform the below steps:-

  1. Launch browser. Here I have launched the Chrome browser.
  2. Launch any URL. I launched Google URL.
  3. Open dev tool.
  4. Click on the “console” tab.
  5. In the console, type “document.URL” command and hit enter. You will give the current URL.

Selenium Code

To run JavaScript command, Selenium WebDriver provides a method called “executeScript()” which is declared in JavascriptExecutor interface.

Output

Current URL is : https://www.google.com/

Please subscribe to my YouTube channel Retarget Common to learn from my video tutorials.

Below are important end to end tutorials for Testers:-

Selenium Tutorials

Rest Assured Tutorials

Postman Tutorials

TestNG Tutorials

If you have any doubt, feel free to comment below.
If you like my posts, please like, comment, share and subscribe.
#ThanksForReading
#HappyLearning

Author: Amod Mahajan

A software Tester who is paid to judge products developed by others. Currently getting paid in American Dollars. Writing technical posts and creating YouTube videos are my hobbies.

Leave a Reply

Please wait...

Subscribe to new posts to become automation expert

Want to be notified when my new post is published? Get my posts in your inbox.