Autofocus input text field

Autofocus the first visible input text field when a page is loaded

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

  1. // ==UserScript==
  2. // @name Autofocus input text field
  3. // @description Autofocus the first visible input text field when a page is loaded
  4. // @version 1.0.3
  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.  
  13. document.addEventListener('DOMContentLoaded', function() {
  14. if (TEXT_FIELD.indexOf(document.activeElement.type) >= 0)
  15. return;
  16. // find text inputs inside visible DOM containers
  17. var inputs = document.getElementsByTagName('input');
  18. var first;
  19. for (var i=0, input, il=inputs.length; i<il && (input=inputs[i]); i++)
  20. if (TEXT_FIELD.indexOf(' '+input.type+' ') >= 0) {
  21. var n=input, style;
  22. while (n && n.style && (style=getComputedStyle(n)) && style.display!='none' && style.visibility!='hidden')
  23. n = n.parentNode;
  24. if (!n || !n.style) {
  25. 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)
  26. || (input.value && input.name == first.name && (!input.form && !first.form || input.form.action == first.form.action))) {
  27. first = input;
  28. if (first.value)
  29. break;
  30. }
  31. }
  32. }
  33. if (first) {
  34. first.focus();
  35. first.select();
  36. }
  37. });