Greasy Fork

Backpack.tf Keyboard Navigator

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

当前为 2023-09-11 提交的版本,查看 最新版本

// ==UserScript==
// @name         Backpack.tf Keyboard Navigator
// @version      1.5.0
// @description  Allows for the use of the left and right keyboard keys to navigate backpack.tf classifieds and premium search pages.
// @author       Matt-RJ
// @match        *.backpack.tf/*
// @namespace https://greasyfork.org/users/313414
// ==/UserScript==

function goToPage(dir) {
  if (dir.toLowerCase() !== 'next' && dir.toLowerCase() !== 'previous') {
    console.error('Backpack.tf Page Navigator | Invalid direction');
    return;
  }
  const currentUrl = new URL(window.location.href);
  if (currentUrl.searchParams.has('page')) { // For regular backpack.tf
    const currentPage = parseInt(currentUrl.searchParams.get('page'), 10);
    if (dir.toLowerCase() === 'next') {
      currentUrl.searchParams.set('page', currentPage + 1);
    } else {
      if (currentPage - 1 < 1) {
        console.log('Backpack.tf Page Navigator | No previous page');
        return; // Do nothing if there is no previous page
      }
      currentUrl.searchParams.set('page', currentPage - 1);
    }
  } else if (currentUrl.searchParams.has('first') && currentUrl.searchParams.has('rows')) { // For next.backpack.tf
    const first = parseInt(currentUrl.searchParams.get('first'), 10);
    const rows = parseInt(currentUrl.searchParams.get('rows'), 10);
    if (dir.toLowerCase() === 'next') {
      currentUrl.searchParams.set('first', first + rows);
    } else {
      if (first - rows < 0) {
        console.log('Backpack.tf Page Navigator | No previous page');
        return; // Do nothing if there is no previous page
      }
      currentUrl.searchParams.set('first', first - rows);
    }
  }
  console.log(`Backpack.tf Page Navigator | Going to ${dir} page`);
  window.location.href = currentUrl.toString();
}

(function () {
  'use strict';
  window.onkeydown = (e) => {
    // Ignore key presses if the user is typing in a text box
    if (['INPUT', 'TEXTAREA'].includes(e.target.tagName)) {
      return;
    }

    if (e.keyCode === 37) { // Left arrow
      goToPage('previous');
    } else if (e.keyCode === 39) { // Right arrow
      goToPage('next');
    }
  };
})();