chrome.browserAction.onClicked.addListener(function(){ var objList = document.getElementsByClassName("anyClass"); alert(objList.length) }) 

By clicking on the extension icon, an alert should be displayed showing the number of elements on the page with the class. But it always returns 0. If you register in the console

 var objList = document.getElementsByClassName("anyClass") 

That list is created. If through expansion then no. What am I doing wrong?

  • looking for the wrong document - Grundy
  • That is, the code is executed for the extension button itself (browserAction)? Tell me then, please, what I missed so that the code runs for the open tab. - Prodigy

1 answer 1

Somehow, not tested:

 chrome.browserAction.onClicked.addListener(function(tab){ chrome.tabs.executeScript(tab.id, { code: ` var objList = document.getElementsByClassName("anyClass"); alert(objList.length)` }); })