【问题标题】:Highlighting Text on a Page Using Javascript使用 Javascript 突出显示页面上的文本
【发布时间】:2021-12-01 18:22:08
【问题描述】:

我正在开发一个 Google Chrome 扩展程序,它将突出显示列表中的某些单词。但是,我无法突出显示这些词。我目前仅使用一个单词进行测试,但无济于事。我的代码永远不会超过 background.js 文件中的if ("undefined" != typeof localStorage)。它只是跳过它下面的整个代码部分。

popup.js

document.addEventListener("DOMContentLoaded", function() {
    loadKeywords();

    document.getElementById("buttonScan").addEventListener("click", function() {
        scanForWords();

        chrome.runtime.sendMessage({
            "message": "getWords",
            "remove": true
        });
    });
});

common.js

    function loadKeywords() {
    if ("undefined" != typeof localStorage) {
        localStorage.setItem("keywords", "washington");
        localStorage.setItem("foreground", "lightgrey");
        localStorage.setItem("background", "#ffff00");
        localStorage.setItem("numOfWords", true);
}

function scanForWords() {
    if ("undefined" != typeof localStorage) {
        localStorage.setItem("keywords", "washington");
        localStorage.setItem("foreground", "lightgrey");
        localStorage.setItem("background", "#ffff00");
        localStorage.setItem("numOfWords", true);
    }
}

background.js

    chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if ("getWords" == request.message) {
        if ("undefined" != typeof localStorage) {
            chrome.tabs.query({
                    "active": true,
                    "currentWindow": true
                },
                function(tabs) {
                    if ("undefined" != typeof tabs[0].id && tabs[0].id) {
                        var wordCount = localStorage.getItem("wordCount");
                        wordCount = "true" == showOccurrences || null == showOccurrences;

                        chrome.tabs.sendMessage(tabs[0].id, {
                            "message": "returnWords",
                            "remove": request.remove,
                            "keywords": localStorage.getItem("keywords"),
                            "foreground": localStorage.getItem("foreground") || "red",
                            "background": localStorage.getItem("background") || "#lightblue",
                            "showOccurrences": showOccurrences
                        });
                    }
                }
            );
        }
    }
});

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if ("numOfWords" == request.message) {
        var wordCount = localStorage.getItem("numOfWords");
        wordCount = "true" == wordCount || null == wordCount;

        chrome.browserAction.setBadgeText({
            "text": wordCount && request.occurrences ? String(request.occurrences) : "",
            "tabId": sender.tab.id
        });
    }
});

content.js

    function keywordsHighlighter(options, remove) {
    var occurrences = 0;

    // Based on "highlight: JavaScript text higlighting jQuery plugin" by Johann Burkard.
    // http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html
    // MIT license.
    function highlight(node, pos, keyword, options) {
        var span = document.createElement("span");
        span.className = "highlighted";
        span.style.color = options.foreground;
        span.style.backgroundColor = options.background;

        var highlighted = node.splitText(pos);
        /*var afterHighlighted = */highlighted.splitText(keyword.length);
        var highlightedClone = highlighted.cloneNode(true);

        span.appendChild(highlightedClone);
        highlighted.parentNode.replaceChild(span, highlighted);

        occurrences++;
    }

    function addHighlights(node, keywords, options) {
        var skip = 0;

        var i;
        if (3 == node.nodeType) {
            for (i = 0; i < keywords.length; i++) {
                var keyword = keywords[i].toLowerCase();
                var pos = node.data.toLowerCase().indexOf(keyword);
                if (0 <= pos) {
                    highlight(node, pos, keyword, options);
                    skip = 1;
                }
            }
        }
        else if (1 == node.nodeType && !/(script|style|textarea)/i.test(node.tagName) && node.childNodes) {
            for (i = 0; i < node.childNodes.length; i++) {
                i += addHighlights(node.childNodes[i], keywords, options);
            }
        }

        return skip;
    }

    function removeHighlights(node) {
        var span;
        while (span = node.querySelector("span.highlighted")) {
            span.outerHTML = span.innerHTML;
        }

        occurrences = 0;
    }

    if (remove) {
        removeHighlights(document.body);
    }

    var keywords = options.keywords.split(",");
    delete options.keywords;
    addHighlights(document.body, keywords, options);

    chrome.runtime.sendMessage({
        "message": "numOfWords",
        "occurrences": occurrences
    });
}

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if ("returnWords" == request.message) {
        if ("undefined" != typeof request.keywords && request.keywords) {
            keywordsHighlighter({
                    "keywords": request.keywords,
                    "foreground": request.foreground,
                    "background": request.background
                },
                request.remove
            );
        }
    }
});

chrome.runtime.sendMessage({
    "message": "getWords",
    "remove": false
});

非常感谢您在正确方向上的任何帮助。在过去的一个小时里,我一直在用头撞墙,试图弄清楚为什么它不会前进。

【问题讨论】:

标签: javascript highlight


【解决方案1】:

我不知道 localStorage 是否在您的代码中的其他地方定义,但如果没有,您需要在清单中请求后通过 chrome. 访问它:

{
  "name": "My extension",
  ...
  "permissions": [
    "storage"
  ],
  ...
}

然后:

chrome.storage.local.set({key: value}, function() {
  console.log('Value is set to ' + value);
});

chrome.storage.local.get(['key'], function(result) {
  console.log('Value currently is ' + result.key);
});

参考:https://developer.chrome.com/docs/extensions/reference/storage/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-04
    • 2013-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-21
    • 1970-01-01
    相关资源
    最近更新 更多