Auto-focus on first textbox

Auto-focuses on the first/main textbox of a site

当前为 2015-01-30 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Auto-focus on first textbox
  3. // @namespace http://userscripts.org/users/23652
  4. // @description Auto-focuses on the first/main textbox of a site
  5. // @include http://*
  6. // @include https://*
  7. // @exclude file://*
  8. // @copyright JoeSimmons
  9. // @version 1.0.3
  10. // @license GPL version 3 or any later version; http://www.gnu.org/copyleft/gpl.html
  11. // ==/UserScript==
  12.  
  13. /* CHANGELOG
  14.  
  15. 1.0.3 (1/30/2015)
  16. - added some small delays for YouTube for it to work
  17. - removed the use of JSL; it's unnecessary
  18.  
  19. */
  20.  
  21. (function () {
  22. // make sure the page is not in a frame
  23. if (window.frameElement || window !== window.top) { return; }
  24.  
  25. var domain = window.document.domain,
  26. rDomain = /([a-z0-9]+\.)?([a-z0-9-]+(\.[a-z0-9]+)+)$/,
  27. site = '',
  28. delay = 99, // by default, use a small delay to make sure the site's onload stuff is done
  29. e = document.querySelector('input[type="text"], input[type="search"], textarea'),
  30. len;
  31.  
  32. // grab the domain minus the subdomain
  33. if ( domain.match(rDomain) ) {
  34. site = domain.match(rDomain)[2];
  35. }
  36.  
  37. // this section is for sites that require special attention ;)
  38. switch (site) {
  39. case 'youtube.com': {
  40. e = document.querySelector('#masthead-search-term');
  41. delay = 750;
  42. break;
  43. }
  44. case 'userscripts.org': case 'google.com': {
  45. e = document.querySelector('input[name="q"]');
  46. break;
  47. }
  48. case 'facebook.com': {
  49. e = document.querySelector('textarea[name="xhpc_message_text"], textarea[name="xhpc_message"]');
  50. delay = 750;
  51. break;
  52. }
  53. }
  54.  
  55. // if the element exists and is visible (in-view), then proceed
  56. if (e && Math.max(e.offsetWidth, e.offsetHeight) > 0) {
  57. len = e.value.length;
  58.  
  59. if (typeof e.focus === 'function') {
  60. // some sites require a delay
  61. window.setTimeout(function (element, length) {
  62. // focus the text box
  63. element.focus();
  64.  
  65. // highlight its text
  66. if (length > 0 && typeof element.setSelectionRange === 'function') {
  67. element.setSelectionRange(0, length);
  68. }
  69. }, delay, e, len);
  70. }
  71. }
  72. }());