0

我一直在尝试创建一个基于 GeckoView 的网络扩展,用于在我的 facebook 移动提要上下载图像。因此,作为第一次运行,我使用谷歌浏览器中的 Inspect> 控制台来测试一个简单的脚本来检测所有图像并使边框变为红色:

var imgs=document.getElementsByTagName("img");
for (i=0;i<imgs.length;i++)
{
imgs[i].style.border="3px solid red";
}  

上面的代码行在许多网站(包括 facebook)的 google chrome 控制台中运行良好。但是,当我将 JS 代码打包为 geckoview Web 扩展的内容脚本时,它根本无法工作!以下是我迄今为止尝试过的所有技巧:

  1. 通过包括以下内容确保在文档之后加载 content_script:

      "content_scripts": [{
           "run_at": document_end,
          "js": ["myscript.js"],
          "matches": ["<all_urls>"],
          "match_about_blank": true,
          "all_frames": true }]
    

    也试过:"run_at": document_idle.

  2. 通过使用确保“X 射线”视力关闭document.wrappedJSObject.getElementsByTagName("img")

  3. 取消注册和重新注册网络扩展。

这些都不起作用。有趣的是,网络扩展适用于除 facebook 之外的所有其他网站!所以我怀疑我有两个问题之一:

  1. Facebook 在隐藏 DOM 方面做得非常好!
  2. GeckoView 无法访问“动态生成”图像元素的 DOM。

任何帮助,将不胜感激 :)

4

1 回答 1

1

我刚刚对其进行了测试,并且扩展程序对我来说是书面的。您编写的代码只会在加载时捕获页面上预设的图像,但 Facebook 网站的大部分内容都是在此之后动态加载的,这可能是您没有看到大多数图像添加边框的原因。

您需要一种方法来观察 DOM 的变化并捕获动态添加的所有新图像,以便按照您的预期方式工作。例如使用MutationObserverhttps ://developer.mozilla.org/en-US/docs/Web/API/MutationObserver

function observe() {
  var imgs = document.getElementsByTagName("img");
  for (i = 0; i < imgs.length; i++) {
    imgs[i].style.border="3px solid red";
  }
}

// Select the node that will be observed for mutations
const targetNode = document.body;

// Options for the observer (which mutations to observe)
const config = { attributes: true, childList: true, subtree: true };

// Create an observer instance linked to the callback function
const observer = new MutationObserver(observe);

// Start observing the target node for configured mutations
observer.observe(targetNode, config);

// Trigger for static content
observe();
于 2020-02-12T17:59:57.007 回答