Search code examples
javascripthtmlparsinggoogle-chrome-extension

Chrome extension's contentScript won't get querySelectorAll


I have problems getting results from document.querySelectorAll

The following code is working perfect inside browser's debugging console:

document.querySelectorAll("td.answer-text > div").forEach(function(el, i, arr)
    {
        var a = el.innerHTML;
        a = a.replaceAll('<div>', '');
        a = a.replaceAll('</div>', '');
        a = a.replaceAll('<br>', '');
        a = a.replaceAll('&nbsp;', ' ');
        console.log(a);
    });

Inside of contentScript.js I get empty array result: Array(0)

window.addEventListener ("load", function()
{
    document.querySelectorAll("td.answer-text > div").forEach(function(el, i, arr)
    {
        var a = el.innerHTML;
        a = a.replaceAll('<div>', '');
        a = a.replaceAll('</div>', '');
        a = a.replaceAll('<br>', '');
        a = a.replaceAll('&nbsp;', ' ');
        console.log(a);
    });
}, false);

manifest.json

{
"manifest_version": 2,
...
 "content_scripts": [{
  "all_frames": true,
  "js": ["content.js"],
  "matches": [ "http://*/*", "https://*/*" ],
  "run_at": "document_end"
}],
"background": {
 ...
],
"persistent": false
},
"options_page": "options.html",
"permissions": [ "activeTab", "storage", "tabs", "webNavigation",  " 
 <all_urls>" ]

}

Any suggestions?


Solution

  • The items may be generated after load event, you can use MutationObserver to wait for it to be inserted.

    // target element is delay loaded
    window.addEventListener ("load", function something_is_delay_loaded()
    {
       setTimeout(()=>document
         .getElementById('parent')
         .insertAdjacentHTML('afterbegin', '<div id=target>delay loaded item</div>')
       , 1000)
    })
    
    //so you would not found it on load
    window.addEventListener ("load", function you_would_not_found_it_on_load()
    {
      console.log('onload:', document.getElementById('target'))
    })
    
    window.addEventListener ("load", function()
    {
       let mutationObserver = new MutationObserver(
          mutations=>mutations.forEach(x=>console.log('nodes add:', [...x.addedNodes]))
       )
       mutationObserver.observe(document.getElementById('parent'),{childList:true})
    })
    <div id=parent></div>