【问题标题】:Chrome Extension And Dom CaptureChrome 扩展和 Dom 捕获
【发布时间】:2021-09-05 07:04:09
【问题描述】:

我为我的一个页面创建了 chrome 扩展程序。我在页面上的 dom 元素中获取数据并查询 api 并将其回调。在我获取数据的网站上,在页面之间切换时页面不会重新加载。所以我无法在foreground.js中捕获Dom加载或位置更改,因为页面没有刷新,我通过超时解决了我的问题。foreground.js中的dom仅在页面刷新时触发。我在settimeout中写的代码是在页面切换的时候触发的。我怎样才能在不超时的情况下解决这个问题?

background.js 代码

chrome.tabs.onUpdated.addListener((tabId, changeInfo,tab) => {
                if(changeInfo.status == "complete" && tab.status == "complete") {
                chrome.scripting.executeScript({
                    target: {tabId: tabId},
                    files: ["./foreground.js"]
                })
            }
});

foreground.js 代码

document.addEventListener("DOMContentLoaded", () => { alert('Dom'); }); //not working

window.addEventListener('locationchange', function(){
  console.log('location changed!');
}) //not working

setTimeout(() => {
let find = document.querySelector(".contentsdetailscontainer").textContent;
},1000); //this is working

【问题讨论】:

  • 是否有问题隐藏在某处?
  • 如何在不超时的情况下解决这个问题?
  • 但是有什么问题?您正在显示与“不工作”代码无关的“工作”代码,它们是完全不相关的函数调用,在不同的对象上。那么你到底在这里问什么?你怎么知道“工作”代码有效?它分配了一个局部范围的变量,对它不做任何事情,然后该变量再次被清理。该代码中没有任何内容可以证明它甚至可以运行。
  • 我的问题是在刷新页面之前我无法在 settimeout 之外捕获 dom 负载。我想捕获 dom 负载,以便我可以在页面上的元素内获取数据。否则元素为空。

标签: javascript jquery google-chrome-extension


【解决方案1】:

foreground.js 在document.readyStatecomplete 时执行,这意味着DOMContentLoaded 已经被触发了。

如果此时所需的元素在 DOM 中不存在,您可以使用 Mutation Observer 并等待它。

这是一个简单的例子(非常低效,因为它观察整个身体,如果只有特定元素发生变化,你应该观察它,所以只作为指导):

var nodeFound = false;
const observer = new MutationObserver(() =>
{
  const node = document.querySelector(".contentsdetailscontainer");
  if (node && node.textContent)
  {
    if (!nodeFound)
    {
      //only show alert once per new page.
      alert("node found");
      nodeFound = true;
    }
  }
  else
  {
    nodeFound = false; //reset in case page updated again
  }
});

observer.observe(document.body, {subtree: true, childList: true});

【讨论】:

  • 我刚刚了解了 MutationObserver,这是一个非常好的功能,但不幸的是,这不是我的问题的解决方案。我的问题是在页面刷新之前我无法捕获 dom 负载。我想捕获 dom 负载,以便我可以在页面上的元素内获取数据。否则元素为空。
  • foreground.js 在document.readyStatecomplete 时执行,这意味着DOMContentLoaded 已被触发。如果此时所需的元素不存在,您可以使用 MutationObserver 等待它被插入到 DOM 中。
猜你喜欢
  • 2017-03-15
  • 2013-11-14
  • 2014-12-26
  • 2023-03-10
  • 2012-01-09
  • 1970-01-01
  • 1970-01-01
  • 2014-11-19
相关资源
最近更新 更多