Skip to content

Instantly share code, notes, and snippets.

@eyssette
Last active January 19, 2023 23:36
Show Gist options
  • Save eyssette/1d8a4e87b3617ca3886f92fa85e2bcea to your computer and use it in GitHub Desktop.
Save eyssette/1d8a4e87b3617ca3886f92fa85e2bcea to your computer and use it in GitHub Desktop.
A bookmarklet to highlight common and proper nouns on a webpage
  1. Copy the code below:
javascript:(function(){
    var script = document.createElement('script');
    script.src = 'https://cdn.jsdelivr.net/npm/compromise@latest/builds/compromise.min.js';
    document.body.appendChild(script);

    script.onload = function() {
        var textNodes = document.evaluate('//body//text()', document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
        for (var i = 0; i < textNodes.snapshotLength; i++) {
            var node = textNodes.snapshotItem(i);
            var words = node.nodeValue.split(' ');
            for (var j = 0; j < words.length; j++) {
                var nlp_word = nlp(words[j]);
                if (nlp_word.topics().out("text") || nlp_word.match('#ProperNoun').out("text") || (nlp_word.nouns().out("text") && nlp_word.out("text").match(/^\p{Lu}[\p{Ll}'’]/u) && !nlp_word.pronouns().out("text")) ) {
                    var span = document.createElement("span");
                    span.style.color = "orange";
                    var textnode = document.createTextNode(words[j]);
                    span.appendChild(textnode);
                    node.parentNode.insertBefore(span, node);
                } else if (nlp_word.nouns().out("text") && !nlp_word.pronouns().out("text")) {
                    var span = document.createElement("span");
                    span.style.color = "red";
                    var textnode = document.createTextNode(words[j]);
                    span.appendChild(textnode);
                    node.parentNode.insertBefore(span, node);
                } else {
                    var textnode = document.createTextNode(words[j]);
                    node.parentNode.insertBefore(textnode, node);
                }
                if(j !== words.length -1){
                    var space = document.createTextNode(" ");
                    node.parentNode.insertBefore(space, node);
                }
            }
            node.parentNode.removeChild(node);
        }
    };
})();
  1. Create a new bookmark.
  2. Set the bookmarklet name and paste the above as the URL.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment