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.

package com.mse.codes;

import org.openqa.selenium.chrome.ChromeDriver;

import io.github.bonigarcia.wdm.WebDriverManager;

public class GetCurrentURLUsingJavascript {
	
	public static void main(String[] args) {
		
		// Launch browser
		WebDriverManager.chromedriver().setup();
		ChromeDriver driver = new ChromeDriver();
		
		// Load URL
		driver.get("https://www.google.com/");
		
		// JavaScript command to get URL
		String cURL = (String) driver.executeScript("return document.URL");
		System.out.println("Current URL is : "+cURL);
		
		driver.quit();
	}

}

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

Leave a Reply

Your email address will not be published. Required fields are marked *