Backpack.tf Keyboard Navigator

Allows for the use of the left and right keyboard keys to navigate backpack.tf classifieds and premium search pages.

  1. // ==UserScript==
  2. // @name Backpack.tf Keyboard Navigator
  3. // @author https://github.com/Matt-RJ
  4. // @namespace https://github.com/Matt-RJ/tampermonkey-scripts/blob/master/backpack-tf-page-navigator
  5. // @version 1.6.0
  6. // @description Allows for the use of the left and right keyboard keys to navigate backpack.tf classifieds and premium search pages.
  7. // @match *.backpack.tf/*
  8. // ==/UserScript==
  9.  
  10. function goToPage(dir) {
  11. if (dir.toLowerCase() !== 'next' && dir.toLowerCase() !== 'prev') {
  12. console.error('Backpack.tf Page Navigator | Invalid direction');
  13. return;
  14. }
  15. console.log(`Backpack.tf Page Navigator | Going to ${dir} page`);
  16. const url = new URL(window.location.href);
  17. if (url.searchParams.has('page')) { // For regular backpack.tf
  18. const currentPage = parseInt(url.searchParams.get('page'), 10);
  19. if (dir.toLowerCase() === 'next') {
  20. url.searchParams.set('page', currentPage + 1);
  21. } else {
  22. url.searchParams.set('page', currentPage - 1 < 1 ? 1 : currentPage - 1);
  23. }
  24. } else if (url.searchParams.has('first') && url.searchParams.has('rows')) { // For next.backpack.tf
  25. const first = parseInt(url.searchParams.get('first'), 10);
  26. const rows = parseInt(url.searchParams.get('rows'), 10);
  27. if (dir.toLowerCase() === 'next') {
  28. url.searchParams.set('first', first + rows);
  29. } else {
  30. url.searchParams.set('first', first - rows < 0 ? 0 : first - rows);
  31. }
  32. } else {
  33. // Some next.backpack.tf features do not contain URL pagination - clicking any next/prev buttons instead.
  34. let button = document.querySelector(`.p-paginator-${dir.toLowerCase()}`) ||
  35. document.getElementsByClassName(`fa fa-angle-${dir === 'next' ? 'right' : 'left'}`)[0];
  36. if (!button) {
  37. console.log(`Backpack.tf Page Navigator | No ${dir} button`);
  38. return;
  39. }
  40. button.click();
  41. return;
  42. }
  43. window.location.href = url.toString();
  44. }
  45.  
  46. (function () {
  47. 'use strict';
  48. window.onkeydown = (e) => {
  49. // Ignore key presses if the user is typing in a text box
  50. if (['INPUT', 'TEXTAREA'].includes(e.target.tagName)) {
  51. return;
  52. }
  53.  
  54. if (e.keyCode === 37) { // Left arrow
  55. goToPage('prev');
  56. } else if (e.keyCode === 39) { // Right arrow
  57. goToPage('next');
  58. }
  59. };
  60. })();