Last active
September 29, 2016 13:51
-
-
Save florentbr/ed424ce3a5d10a9b7f3330f1226ba166 to your computer and use it in GitHub Desktop.
Selenium - Focus the next/previous element when the Tab key is not supported
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
JS_TAB_FOCUS = open('tab-focus.js', 'r').read() | |
# focus the next element | |
elem_next = driver.execute_scrit(JS_TAB_FOCUS, false) | |
elem_next.send_keys("abcd") | |
# focus the previous element | |
elem_prev = driver.execute_scrit(JS_TAB_FOCUS, true) | |
elem_prev.click() | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var backward = arguments[0]; | |
var active = document.activeElement; | |
var event = document.createEvent('KeyboardEvent'); | |
event.initKeyEvent('keydown', true, true, document.defaultView, false, false, backward, false, 9, 0); | |
if (!active.dispatchEvent(event)) return document.activeElement; | |
var elms = [].slice.call(document.querySelectorAll('a,area,button,input,object,select,optgroup,textarea,[tabindex]')) | |
.filter(function (e) { return !e.disabled && !e.readOnly && e.tabIndex >= 0 && e.offsetWidth > 0 && e.offsetHeight > 0 }) | |
.sort(function (a, b) { return (a.tabIndex || 0x1fffffff) - (b.tabIndex || 0x1fffffff) }); | |
active.blur(); | |
emit('blur', active); | |
var n = elms.length + elms.indexOf(active); | |
for (var attempts = 10; attempts--; ) { | |
var next = elms[(n += (backward ? - 1 : 1)) % elms.length]; | |
next.focus(); | |
if (document.activeElement === next) { | |
emit('focus', next); | |
return next; | |
} | |
} | |
return null; | |
function emit(type, target) { | |
var event = document.createEvent('Event'); | |
event.initEvent(type, true, true); | |
return target.dispatchEvent(event); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment