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 ':'
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:
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();
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();