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

My name is Amod Mahajan and I am an IT employee with 6+ years of experience in Software testing and staying in Bengaluru. My area of interest is Automation testing. I started from basics and went through so many selenium tutorials. Thanks to Mukesh Otwani as his tutorials are easy and cover basics to advance. I have habit of exploring concepts by deep diving. I used to make notes. I thought of sharing my knowledge through posts and now I am here. #KeepLearning #ShareLearning

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.

How To Get Current URL Using JavaScript In Selenium Java?

by Amod Mahajan time to read: 1 min
0
%d bloggers like this: