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

当前为 2016-03-11 提交的版本,查看 最新版本

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