左右鍵翻頁 Navigate with Arrow Keys

使用左右箭頭鍵來翻頁

目前为 2024-09-27 提交的版本。查看 最新版本

// ==UserScript==
// @name         左右鍵翻頁 Navigate with Arrow Keys
// @namespace    http://tampermonkey.net/
// @version      0.2
// @description  使用左右箭頭鍵來翻頁
// @author       Your Name
// @match        *://*/*
// @grant        none
// ==/UserScript==
 
(function() {
    'use strict'; // 使用嚴格模式

    // 定義包含「上一章」、「上一頁」和「上一页」文本的陣列
    const prevTexts = ['上一章', '上一頁', '上一页'];
    // 定義包含「下一章」、「下一頁」和「下一页」文本的陣列
    const nextTexts = ['下一章', '下一頁', '下一页'];

    // 使用 XPath 查找包含特定文本的按鈕
    function findButton(texts) {
        return document.evaluate(
            // 使用 XPath 表達式查找包含任意指定文本的 <a> 標籤
            `//a[contains(text(), "${texts.join('") or contains(text(), "')}")]`,
            document, // 在整個文件中查找
            null, // 不需要命名空間解析器
            XPathResult.FIRST_ORDERED_NODE_TYPE, // 返回第一個匹配的節點
            null // 不需要結果參數
        ).singleNodeValue; // 獲取單個節點的值
    }

    // 監聽鍵盤按鍵事件
    document.addEventListener('keydown', function(event) {
        if (event.key === 'ArrowLeft') { // 當按下左箭頭鍵時
            const prevButton = findButton(prevTexts); // 查找上一頁按鈕
            if (prevButton) prevButton.click(); // 如果找到按鈕,則點擊它
        } else if (event.key === 'ArrowRight') { // 當按下右箭頭鍵時
            const nextButton = findButton(nextTexts); // 查找下一頁按鈕
            if (nextButton) nextButton.click(); // 如果找到按鈕,則點擊它
        }
    });
})();