Search code examples
javascripthtmlcssgoogle-chromegoogle-chrome-extension

How To Scan a Page For Terms And Display Them - Javascript - Chrome Extension


I am trying at the moment to make a google chrome extension and have hit a roadblock.

I want the extension to scan the page for 3 terms and display them in a div, but I do not have much knowledge in JavaScript and need help.


Solution

  • const globalWordsStore = new Map();
    const setOfWords = ['Hello', 'World']
    function populateStore(el){
      let n;
      let a=[];
      let walk=document.createTreeWalker(el,NodeFilter.SHOW_TEXT,null,false);
      while(n=walk.nextNode()) {
        const arrayOfWords = n.data.trim().split(" ");
        arrayOfWords.forEach((ele) => {
          if(setOfWords.includes(ele)){
            if(globalWordsStore.has(ele)){
            globalWordsStore.set(ele, globalWordsStore.get(ele) + 1);
          } else {
            globalWordsStore.set(ele, 1);
          }
          }
        })
      }
    }
    
    populateStore(document.getElementsByTagName('body')[0]);
    
    for (const [key, value] of globalWordsStore.entries()) {
      // key --> word
      // value --> count of that partivular word
      console.log(key, value);
    }

    Here Map will be storing all the words and their count. Here the approach is, to first pick out all the text nodes from the DOM (which are a child of the body element), then extract the text from it, next I created an array using words in the entire text and then used globalWordsStore to the store of occurrence of each individual word and this I did for all the text nodes in the DOM.

    More about CreateTreeWalker