3

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

ee clipse
  • 245
  • 1
  • 3
  • 14

4 Answers4

6

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.

Community
  • 1
  • 1
James
  • 2,756
  • 17
  • 19
2

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');")
Paras
  • 3,197
  • 2
  • 20
  • 30
  • Hi Paras, I have similar problem and I tried to set attribute like driver.execute_script("arguments[0].setAttribute('target', 'self')", el) el.click() but no luck I can still see multiple windows. Any more suggestions? – Manvi May 30 '18 at 22:03
  • tell me what issue you are facing. – Paras May 31 '18 at 03:35
  • Please refer : https://stackoverflow.com/questions/50611045/python-selenium-opens-a-new-window-on-click-instead-of-tab – Manvi May 31 '18 at 14:48
0

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.)

Prashanth Sams
  • 19,677
  • 20
  • 102
  • 125
0
WebDriverManager.firefoxdriver().setup();
FirefoxOptions options = new FirefoxOptions();
options.addPreference("browser.link.open_newwindow", 1);               
driver = new FirefoxDriver(options);
  • Code-only answers are generally frowned upon on this site. Could you please edit your answer to include some comments or explanation of your code? Explanations should answer questions like: What does it do? How does it do it? Where does it go? How does it solve OP's problem? See: [How to anwser](https://stackoverflow.com/help/how-to-answer). Thanks! – Eduardo Baitello Nov 19 '19 at 12:41