Highlight Sentence on Hover

Highlights sentence when mouse hovers over it

当前为 2023-12-20 提交的版本,查看 最新版本

// ==UserScript==
// @name        Highlight Sentence on Hover
// @namespace   Violentmonkey Scripts
// @match       *://*/*
// @author     https://github.com/b-y-f
// @grant       none
// @version     1.2
// @license     MIT
// @description Highlights sentence when mouse hovers over it
// ==/UserScript==

function getSentences(node) {
    return node.innerText.split(/(?<=[\.!\?])\s/);
}

function wrapSentences(node) {
    let html = node.innerHTML;
    html = html.replace(/(?<=[\.!\?])\s/g, '</span> <span>');
    if (window.trustedTypes && trustedTypes.createPolicy) { // Check if Trusted Types is enabled
        var policy = trustedTypes.createPolicy('myPolicy', {
            createHTML: (string) => string, // Policy that allows any string
        });
        node.innerHTML = policy.createHTML('<span>' + html + '</span>');
    } else {
        node.innerHTML = '<span>' + html + '</span>';
    }
}



function highlightSentence(e) {
    const target = e.target;
    if (target.tagName === 'SPAN') {
        target.style.backgroundColor = e.type === 'mouseover' ? '#B4D5FE' : '';
    }
}

document.body.addEventListener('mouseover', highlightSentence);
document.body.addEventListener('mouseout', highlightSentence);

function doThing(){
    const allParagraphs = document.querySelectorAll('p, li');
    // const textNodes = Array.from(allParagraphs).filter(node => node.attributes.length === 0);
    allParagraphs.forEach(node => wrapSentences(node));
}

window.addEventListener('load', function() {
    doThing();
    console.log('load done');
});

var observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {
        doThing();
        console.log('DOM has changed');
    });
});

var config = { attributes: true, childList: true, characterData: true };
observer.observe(document.body, config);

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址