Chrome 扩展内容脚本不会获取 querySelectorAll

Chrome extension's contentScript won't get querySelectorAll

我无法从 document.querySelectorAll

获取结果

以下代码在浏览器的调试控制台中运行完美:

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

在 contentScript.js 内部我得到空数组结果: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>" ]

}

有什么建议吗?

物品可能会在load事件后生成,您可以使用MutationObserver等待插入。

// 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>