Selenium - Last Resort - codecentric AG Blog
The following example is utilizing the Selenium-Library of the Robot Framework as this results in a very readable example. Of course the same approach could also be used with other Selenium-based libraries. Here a search is performed using Google, where the “Search” button is not clicked the normal (Selenium) way – which would be perfectly possible of course – but the button is clicked using some native keystrokes.
First of all the text to search for is entered to the input field. Assuming the “Search” button cannot be used otherwise, the input field is then first focused and then pressing the TAB key is simulated with Press Key Native 9. Now the “Search” button is focused and the button is then “pressed” by simulating that the RETURN key is pressed. This submits the search query.
It is extremly helpful if there is some known element on the page that can be focused and which can then be used as a starting point for simulating further key events. On the other hand some element always has the focus initially and thus using TAB every element should be accessible on the page. Of course this could get quite ugly. But as usually there are some elements that can be located directly there should be rarely a need using such a brute force approach. The used key codes are defined in java.awt.event.KeyEvent.
Simulating native keystrokes has some quite obvious drawbacks and should really only be used when everything else has failed. But then it could be indeed a kind of “last resort”.