Search code examples
javascriptjavaseleniumselenium-webdriverhref

selenium click link href with javascript


I am a newbie to java and selenium. I am having an issue in clicking a link with javascript in href. Below is the page source:

href="javascript:navigateToDiffTab('https://site_url/medications','Are you sure you want to leave this page without saving your changes?');" tabindex="-1">Medications

Please note: I replaced actual url with "site_url" because of business concerns.

I tried below code but it did not work:

driver.findElement(By.cssSelector("a[href^='javascript:navigateToDiffTab'][href$='site_url/medications']")).click();

I do not want to use id or linkText as those changes with different environments and languages.

Any help would be much appreciated.


Solution

  • Use below code. It is working fine for me:-

    WebElement element= driver.findElement(By.cssSelector("a[href^='javascript:navigateToDiffTab'][href$='site_url/medications']"))
    
    JavascriptExecutor executor = (JavascriptExecutor) driver;
    executor.executeScript("arguments[0].click();", element);
    

    If the above code will not work for you that means there is a problem with your locator. Then try with some other locator or post some HTML code in your question so we can identify that exact locator for you.

    Hope it will help you :)