Focus Input Keybind

Focus to search or a certain text input with forward slash (/) key similar to YouTube.

当前为 2019-06-19 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Focus Input Keybind
  3. // @namespace https://github.com/kittenparry/
  4. // @version 1.1
  5. // @description Focus to search or a certain text input with forward slash (/) key similar to YouTube.
  6. // @author kittenparry
  7. // @match *://*/*
  8. // @grant none
  9. // @license MIT License
  10. // ==/UserScript==
  11.  
  12. /* LIST:
  13. * rarbg.to
  14. * reddit.com
  15. * twitch.tv
  16. * wiktionary.org
  17. */
  18.  
  19. /* CHANGELOG:
  20. * 1.1: +wiktionary.org
  21. * 1.0: initial
  22. */
  23.  
  24. check_focus_input_keybind = (e, val, special) => {
  25. var type = e.target.getAttribute('type');
  26. var tag = e.target.tagName.toLowerCase();
  27. if (type != 'text' && tag != 'textarea') {
  28. if (e.keyCode == 191) { // /
  29. if (special == 'reddit') {
  30. document.getElementById(val).firstChild.focus();
  31. } else if (special == 'selector') {
  32. document.querySelector(val).focus();
  33. } else {
  34. document.getElementById(val).focus();
  35. }
  36. }
  37. }
  38. };
  39.  
  40. /* probably need a better way than simply .includes()
  41. * inid: id or other value of the input element
  42. * inspcl: when inid isn't an id (eg. a class) to specify it
  43. */
  44.  
  45. var current_url = window.location.href;
  46.  
  47. if (current_url.includes('rarbg.to')) {
  48. var inid = 'searchinput';
  49. } else if (current_url.includes('reddit.com')) {
  50. var inid = 'search';
  51. var inspcl = 'reddit';
  52. } else if (current_url.includes('twitch.tv')) {
  53. var inid = 'textarea[class="tw-block tw-border-radius-medium tw-font-size-6 tw-full-width tw-textarea tw-textarea--no-resize"]';
  54. var inspcl = 'selector';
  55. } else if (current_url.includes('wiktionary.org')) {
  56. var inid = 'searchInput';
  57. }
  58.  
  59. if (inid != undefined) {
  60. try {
  61. // pass an empty string for input special so to not repeat the event listener code similar to other script
  62. if (!inspcl) {
  63. var inspcl = '';
  64. }
  65. // keyup instead of keydown to prevent the initial entry of a forward slash to input
  66. window.addEventListener('keyup', (e) => check_focus_input_keybind(e, inid, inspcl), false);
  67. } catch (e) {}
  68. }