0

I am working on a Google Chrome Extension that will highlight certain words in a list. However, I have not been able to get the words to highlight. I am currently using only one single word for testing purposes to no avail. My code never gets past if ("undefined" != typeof localStorage) in the background.js file. It just skips the entire section of code below it.

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
});

Any help in the right direction is much appreciated. I have been beating my head against a wall for the last hour trying to figure out why it won't move forward.

kevorski
  • 816
  • 1
  • 11
  • 29
  • you should be using `if(typeof localStorage !== "undefined")` – slashroot Oct 13 '21 at 09:09
  • 1
    Does this answer your question? [Chrome extension: store data on background](https://stackoverflow.com/questions/11238883/chrome-extension-store-data-on-background) – emptyhua Oct 13 '21 at 09:09

1 Answers1

1

I don't know if localStorage is defined somewhere else in your code but if not, you need to access it via chrome. after you've requested it in the manifest:

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

And then:

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);
});

Reference: https://developer.chrome.com/docs/extensions/reference/storage/

José M. Gilgado
  • 1,314
  • 3
  • 14
  • 21