Focus input text field on Esc

Focus the first visible input text field when you press Esc key, or restore the previously focused element on second press

当前为 2015-04-28 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Focus input text field on Esc
  3. // @description Focus the first visible input text field when you press Esc key, or restore the previously focused element on second press
  4. // @version 1.0.2
  5. // @author wOxxOm
  6. // @namespace wOxxOm.scripts
  7. // @license MIT License
  8. // @run-at document-start
  9. // ==/UserScript==
  10.  
  11. var TEXT_FIELD = ' text number search url ';
  12. var previousElement;
  13. var toFocus;
  14.  
  15. document.addEventListener('keydown', function(e) {
  16. if (e.keyCode != 27 || e.altKey || e.ctrlKey || e.shiftKey || e.metaKey)
  17. return;
  18. // find text inputs inside visible DOM containers
  19. var inputs = document.getElementsByTagName('input');
  20. var visible = [];
  21. for (var i=0, input, il=inputs.length; i<il && (input=inputs[i]); i++)
  22. if (TEXT_FIELD.indexOf(' '+input.type+' ') >= 0) {
  23. var n=input, style;
  24. while (n && n.style && (style=getComputedStyle(n)) && style.display!='none' && style.visibility!='hidden')
  25. n = n.parentNode;
  26. if (!n || !n.style) {
  27. visible.push(input);
  28. if (input.value)
  29. break;
  30. }
  31. }
  32.  
  33. if (visible.length) {
  34. var toFocus = visible[0];
  35. // if empty, try to select an identically named input field with some text (happens on some sites)
  36. if (!toFocus.value)
  37. for (var i in visible)
  38. if (visible[i].value && visible[i].name == toFocus.name
  39. && (!visible[i].form && !toFocus.form || visible[i].form.action == toFocus.form.action)) {
  40. toFocus = visible[i];
  41. break;
  42. }
  43. if (toFocus != document.activeElement) {
  44. // switch to the found input field
  45. previousElement = document.activeElement;
  46. onkeyup(function(){
  47. toFocus.focus();
  48. toFocus.select();
  49. });
  50. } else if (previousElement) {
  51. // restore focus to the element from which we jumped to an input field previously
  52. onkeyup(function(){
  53. document.activeElement.blur(); // in case document.body (page "background") was previously selected
  54. previousElement.focus();
  55. });
  56. }
  57. }
  58.  
  59. // focusing should be done at key-up to prevent the Esc-keydown being also chain-handled by the just focused element
  60. function onkeyup(cb) {
  61. document.addEventListener('keyup', function keyup(e) {
  62. if (e.keyCode == 27) {
  63. document.removeEventListener('keyup', keyup);
  64. cb(e);
  65. }
  66. });
  67. }
  68. });