ee clipse
ee clipse

Reputation: 245

Selenium: Open Link in Same Tab

I am clicking a link via Selenium webdriver and the link opens up a new windows - I want to force the link to open in the same window (and the same tab) is this possible?

Most of the time this does not happen only with a specific link..

Thanks

Upvotes: 3

Views: 19170

Answers (4)

Selenium Steve
Selenium Steve

Reputation: 1

WebDriverManager.firefoxdriver().setup();
FirefoxOptions options = new FirefoxOptions();
options.addPreference("browser.link.open_newwindow", 1);               
driver = new FirefoxDriver(options);

Upvotes: 0

Prashanth Sams
Prashanth Sams

Reputation: 21169

For single-dom element

@driver.execute_script("document.querySelector('your_css_element')[#{index}].setAttribute('target','_blank')")

For multi-dom elements

 your_list_of_elements.each_with_index do |elem, index|
      @driver.execute_script("document.querySelectorAll('your_css_element')[#{index}].setAttribute('target','_blank')")
 end

(note: the above is a ruby snippet, apply the same in your preferred lang.)

Upvotes: 0

Paras
Paras

Reputation: 3235

See if the HTML code is like below, link will open in a different tab/windows depending upon the browser settings.

<a href = "#" target = "_blank">

When a Firefox browser is launched via Selenium Webdriver, the default profile it launches by default has this option enabled. You can create a new firefox profile by disabling this option. In this case the link will open in the same firefox window.

In Chrome driver, new links open in the same window itself.

You can force selenium webdriver to open a link in the same window but to open the link in same tab I don't think you can force it directly without injecting some Javascript. Using Javascript you can update the attribute target to complete your requirement.

If you want to inject Javascript you can use JavaScriptExecutor from Selenium Webdriver API.

((JavaScriptExecutor)driver).executeScript("document.getElementById('ID').setAttribute('target', 'self');")

Upvotes: 2

James
James

Reputation: 2764

Before clicking the link update the link's target property to self and then click it.

For updating the property please refer to this link.

Upvotes: 6

Related Questions