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

目前為 2018-05-22 提交的版本,檢視 最新版本

  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.5
  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 scrollPos;
  15. var first;
  16.  
  17. document.addEventListener('keydown', function(e) {
  18. if (e.keyCode != 27 || e.altKey || e.ctrlKey || e.shiftKey || e.metaKey)
  19. return;
  20. // find text inputs inside visible DOM containers
  21. var inputs = document.getElementsByTagName('input');
  22. for (var i=0, input, il=inputs.length; i<il && (input=inputs[i]); i++) {
  23. var priority = TEXT_FIELD.indexOf(' '+input.type+' ');
  24. if (priority >= 0) {
  25. var n=input, style;
  26. while (n && n.style && (style=getComputedStyle(n)) && style.display!='none' && style.visibility!='hidden')
  27. n = n.parentNode;
  28. if (!n || !n.style) {
  29. 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)
  30. || (input.value && input.name == first.name && (!input.form && !first.form || input.form.action == first.form.action))) {
  31. first = input;
  32. if (first.value)
  33. break;
  34. }
  35. }
  36. }
  37. }
  38.  
  39. if (first) {
  40. if (first != document.activeElement) {
  41. // switch to the found input field
  42. previousElement = document.activeElement;
  43. scrollPos = [scrollX, scrollY];
  44. onkeyup(function(){
  45. first.focus();
  46. first.select();
  47. });
  48. } else if (previousElement) {
  49. // restore focus to the element from which we jumped to an input field previously
  50. onkeyup(function(){
  51. document.activeElement.blur(); // in case document.body (page "background") was previously selected
  52. previousElement.focus();
  53. scrollTo(scrollPos[0], scrollPos[1]);
  54. });
  55. }
  56. }
  57.  
  58. // focusing should be done at key-up to prevent the Esc-keydown being also chain-handled by the just focused element
  59. function onkeyup(cb) {
  60. document.addEventListener('keyup', function keyup(e) {
  61. if (e.keyCode == 27) {
  62. document.removeEventListener('keyup', keyup);
  63. cb(e);
  64. }
  65. });
  66. }
  67. });