Reputation: 331
Page has image with hyperlink and that hyperlink has target="_blank" and every time i press that image loads new firefox and that hyperlink is redirected to that new firefox web and i lose all control of that webpage. Is possilble to remove or change that target="_blank" on hyperlink, bcause i want to load webpage in same webdriver
WebDriver driver = new FirefoxDriver();
driver.get("http://www.page.eu/");
WebElement submit;
submit = driver.findElement(By.xpath("//img[@alt='page']"));
submit.click();
that hyperlink have target="_blank" i need to change that target somehow by using webdriver + javascript maybe or what? is it possible?
edited
thanks for suggestions, but still is this problem i tried to make like Grooveek said but no changes
WebElement labels2 = driver.findElement(By.xpath("//a[@href='http://tahtpage.net']"));
WebElement aa = (WebElement) ((JavascriptExecutor) driver).executeScript("labels2.setAttribute('target','_self')",labels2 );
aa.click();
i have an error org.openqa.selenium.WebDriverException: null (WARNING: The server did not provide any stacktrace information)
i'm not good at javascrit so i think is problem in that executor
Upvotes: 8
Views: 8579
Reputation: 766
I think you should use the SwitchTo().Window as suggested by simeon sinichkin. however, i didn't like his example.Here is simple example.
driver.Navigate().GoToUrl(baseURL);
//Get the Main Window Handle
var baseWindow = driver.CurrentWindowHandle;
// navigate to another window (_blank)
driver.FindElement(By.Id("btn_help")).Click();
Thread.Sleep(2000);
//switch back to Main Window
driver.SwitchTo().Window(baseWindow);
hope that helps
Upvotes: 1
Reputation: 12806
Try the following:
WebElement labels2 = driver.findElement(By.xpath("//a[@href='http://tahtpage.net']"));
WebElement aa = (WebElement) ((JavascriptExecutor) driver).executeScript("arguments[0].setAttribute('target','_self')",labels2 );
aa.click();
You are getting a null exception because you are using labels2
in your javascript, which doesn't exist in that context. By changing it to arguments[0]
Selenium will take the labels2 parameter and reference it in javascript appropriately.
Upvotes: 3
Reputation: 2630
Instead of clicking on the image, you could just directly go to the URL in the link:
WebElement link = (driver.findElement(By.xpath("//img[@alt='page']/parent::*"));
String href = link.getAttribute("href");
driver.get(href);
Upvotes: 4
Reputation: 10094
Evaluating javascript in the window will help you to suppress target=blank links Here's the example from the Webdriver docs
List<WebElement> labels = driver.findElements(By.tagName("label"));
List<WebElement> inputs = (List<WebElement>) ((JavascriptExecutor)driver).executeScript(
"var labels = arguments[0], inputs = []; for (var i=0; i < labels.length; i++){" +
"inputs.push(document.getElementById(labels[i].getAttribute('for'))); } return inputs;", labels);
Adapt it to modify the DOM to throw target="_blank links"
Upvotes: 1