iThome Arrow Key Pager

使用方向鍵前往上一頁(←)、下一頁(→)

您需要先安裝使用者腳本管理器擴展,如 TampermonkeyGreasemonkeyViolentmonkey 之後才能安裝該腳本。

You will need to install an extension such as Tampermonkey to install this script.

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyViolentmonkey 後才能安裝該腳本。

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyUserscripts 後才能安裝該腳本。

你需要先安裝一款使用者腳本管理器擴展,比如 Tampermonkey,才能安裝此腳本

您需要先安裝使用者腳本管理器擴充功能後才能安裝該腳本。

(我已經安裝了使用者腳本管理器,讓我安裝!)

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

(我已經安裝了使用者樣式管理器,讓我安裝!)

// ==UserScript==
// @name         iThome Arrow Key Pager
// @namespace    https://github.com/livinginpurple
// @version      2025.11.27.15
// @description  Navigate iThome pages using Left (←) and Right (→) arrow keys.
// @description:zh-TW 使用方向鍵前往上一頁(←)、下一頁(→)
// @license      WTFPL
// @author       livinginpurple (Refactored by Gemini)
// @match        **://ithelp.ithome.com.tw/*
// @run-at       document-end
// ==/UserScript==

(function() {
    'use strict';

    const CONFIG = {
        SELECTORS: {
            PREV: '.fa-angle-left',
            NEXT: '.fa-angle-right'
        },
        IGNORED_TAGS: ['INPUT', 'TEXTAREA', 'SELECT']
    };

    /**
     * 執行頁面跳轉
     * @param {string} selector CSS 選擇器
     * @param {string} direction 除錯用的方向名稱
     */
    const navigate = (selector, direction) => {
        const targetIcon = document.querySelector(selector);
        const clickableLink = targetIcon?.closest('a') || targetIcon;
        if (clickableLink) {
            clickableLink.click();
        } else {
            alert(`No ${direction} page!`);
        }
    };

    /**
     * 處理鍵盤事件
     * @param {KeyboardEvent} event
     */
    const handleKeydown = (event) => {
        if (event.altKey || event.ctrlKey || event.shiftKey || event.metaKey) return;
        const activeElement = document.activeElement;
        if (activeElement && (
            CONFIG.IGNORED_TAGS.includes(activeElement.tagName) ||
            activeElement.isContentEditable
        )) {
            return;
        }

        switch (event.key) {
            case 'ArrowLeft':
                navigate(CONFIG.SELECTORS.PREV, 'Previous');
                break;
            case 'ArrowRight':
                navigate(CONFIG.SELECTORS.NEXT, 'Next');
                break;
        }
    };

    document.addEventListener('keydown', handleKeydown);
    console.log(`${GM_info.script.name} loaded.`);
})();