Home > Software engineering >  Chrome extension to iterate all paragraphs in an HTML
Chrome extension to iterate all paragraphs in an HTML

Time:09-27

Currently my chrome extension is displaying a paragraph (first one), but wanted to iterate all paragraphs in an HTML and display those.

chrome.tabs.query( {
    active: true,
    lastFocusedWindow: true
},
function(array_of_Tabs) {
    chrome.tabs.executeScript(tab.id, {code: "chrome.runtime.sendMessage(document.getElementsByTagName('p')[0].innerHTML);"}); 
});

chrome.runtime.onMessage.addListener(function(request) {
   document.getElementsByTagName('html')[0].innerHTML = request;
});

I wanted to add something like this in the above js. Pls advice.

let paragraphs = document.getElementsByTagName("p");
for(let i = 0; i < paragraphs.length; i  ) {
  console.log(paragraphs[i].innerText) // Will print the content of each paragraph
}  

CodePudding user response:

You can join all the innerHTML's and message that.

chrome.tabs.query({
    active: true,
    lastFocusedWindow: true
  },
  function(array_of_Tabs) {
    chrome.tabs.executeScript(tab.id, {
      code: `chrome.runtime.sendMessage([...document.getElementsByTagName('p')].reduce(function(agg, elem) {agg.push(elem.innerHTML); return agg; }, []).join("\n<br>"));`
    });
  });

chrome.runtime.onMessage.addListener(function(request) {
  document.getElementsByTagName('html')[0].innerHTML = request;
});

  • Related