Structural Visual Anchors for PressReader

A lightweight userscript that subtly highlights English function words while reading on PressReader.

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Greasemonkey 油猴子Violentmonkey 暴力猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Violentmonkey 暴力猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Userscripts ,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展后才能安装此脚本。

(我已经安装了用户脚本管理器,让我安装!)

Advertisement:

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

(我已经安装了用户样式管理器,让我安装!)

Advertisement:

// ==UserScript==
// @name         Structural Visual Anchors for PressReader
// @namespace    http://tampermonkey.net/
// @version      1.0.0
// @match        *://*.pressreader.com/*
// @description  A lightweight userscript that subtly highlights English function words while reading on PressReader.
// @author       cccccc
// @grant        none
// @run-at       document-end
// @license MIT
// ==/UserScript==

(function () {
    'use strict';

    const targetWords =
        /\b(a|an|the|in|on|at|of|to|for|with|by|from)\b/gi;

    const style = document.createElement("style");
    style.textContent = `
        ::highlight(function-word-anchor) {
            background: transparent !important;
            color: inherit !important;
            text-decoration: underline dotted #888;
            text-underline-offset: 2px;
        }
    `;
    document.head.appendChild(style);

    const highlight = new Highlight();
    CSS.highlights.set("function-word-anchor", highlight);

    function scan() {

        highlight.clear();

        const paragraphs = document.querySelectorAll(`
            p.article-text,
            p.article-text.trimmed
        `);

        paragraphs.forEach(p => {

            const walker = document.createTreeWalker(
                p,
                NodeFilter.SHOW_TEXT
            );

            let node;

            while ((node = walker.nextNode())) {

                const text = node.nodeValue;

                targetWords.lastIndex = 0;

                let match;

                while ((match = targetWords.exec(text))) {

                    const range = new Range();

                    range.setStart(node, match.index);
                    range.setEnd(node, match.index + match[0].length);

                    highlight.add(range);
                }
            }

        });

    }

    let timer;

    const observer = new MutationObserver(() => {

        clearTimeout(timer);

        timer = setTimeout(scan, 200);

    });

    observer.observe(document.body, {
        childList: true,
        subtree: true
    });

    window.addEventListener("load", scan);

    setTimeout(scan, 1000);
    setTimeout(scan, 2500);
    setTimeout(scan, 5000);

})();