Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

135
Views
How to click on a link which should be open in same window using Selenium Java

I'm just self studying and trying to Automate the Flipkart site using Selenium- Java.

So here's the scenario: I want to click on a product link whose attribute is set as Target=_blank.

I want to set it as _self.

I have written one code using JS Executor but getting error in Runtime :

WebElement linkpath = driver.findElement(By.xpath("//div[text()='vivo Y12G (Glacier Blue, 64 GB)']"));

JavascriptExecutor js = (JavascriptExecutor) driver;

js.executeScript("document.getElementByXpath("+linkpath+").setAttribute('target', 'self')");

linkpath.click();

Error:

org.openqa.selenium.JavascriptException: javascript error: Unexpected token ':'

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

The issue with the code is with this line:

js.executeScript("document.getElementByXpath("+linkpath+").setAttribute('target', 'self')");

You are attempting to pass an object (the element identified by your first line of code) instead of an xpath string (getElementByXpath)

You have 2 options:

  1. Declare xpath as a String at the beginning so it can be used for both lines of code that require it
String xpath = "//div[text()='vivo Y12G (Glacier Blue, 64 GB)']"
WebElement linkpath = driver.findElement(By.xpath(xpath));
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("document.getElementByXpath(xpath).setAttribute('target', 'self')");
linkpath.click();
  1. Amend the JavascriptExecutor to use the Webelement object already found as an argument
WebElement linkpath = driver.findElement(By.xpath("//div[text()='vivo Y12G (Glacier Blue, 64 GB)']"));
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].setAttribute('target', 'self')",linkpath);
linkpath.click();
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!