How to open a new tab with Selenium


635
635 points
open a new tab with Selenium
open a new tab with Selenium

How to open a new tab with Selenium

Many of our tests can require to open a new tab and perform some further operations. Seems pretty straight forward , it used to work using window.open with execute_script, well I’m sorry to disappoint you guys but is no longer working in Chrome , will basically show a pop-up with blocked notification.

This is because browsers usually block window.open unless the user interacted with an element for security reasons. I am not sure why it did work via Selenium before.

The approach is basically to insert a link into the page and have selenium to click on it:

path = "/your/path/here"
id = "helper_#{SecureRandom.hex(8)}"
execute_script <<-JAVASCRIPT
  var $helper = $('<a>').attr({ href: #{path.to_json}, id: #{id.to_json}, target: '_blank' });
  $helper.prependTo('body').text('click me').css({ zIndex: 9999, position: 'absolute' });
  setTimeout(function() { $helper.remove() }, 500);
JAVASCRIPT
find("##{id}").click

As you can see the link will get removed in 500 milliseconds so is not going to affect your tests at all.

You might wander if the link gets removed even if the code above that will fail , well , on a page reload yes the link will get removed anyway , so if you start a new scenario with a brand new session the link will not be chunked into your test page.

Happy testing!

If You enjoyed this article , consider other helper articles :

Advertisements

jQuery scroll to element

Ruby Capybara select random value from dropdown

Introducing the Tellurium Selenium Automated Testing Framework

 


Like it? Share with your friends!

635
635 points
Test engineer

0 Comments

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.