iThome Arrow Key Pager

Navigate iThome pages using Left (←) and Right (→) arrow keys.

您需要先安装一个扩展,例如 篡改猴Greasemonkey暴力猴,之后才能安装此脚本。

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

您需要先安装一个扩展,例如 篡改猴暴力猴,之后才能安装此脚本。

您需要先安装一个扩展,例如 篡改猴Userscripts ,之后才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 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.`);
})();