用于操作 Facebook 图像的 Javascript 代码在控制台中有效,但在扩展中无效

标签 javascript facebook dom geckoview

我一直在尝试创建一个基于 GeckoView 的网络扩展,用于在我的 Facebook 移动源上下载图像。因此,作为第一次运行,我在 google chrome 中使用 Inspect> console 来测试一个简单的脚本来检测所有图像并将边框设为红色:

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. 使用 document.wrappedJSObject.getElementsByTagName("img") 确保“X 射线”视觉关闭

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

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

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

如有任何帮助,我们将不胜感激:)

最佳答案

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

您需要一种方法来观察 DOM 的更改并捕获动态添加的所有新图像,以便按照您想要的方式工作。例如。使用MutationObserver:https://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();

关于用于操作 Facebook 图像的 Javascript 代码在控制台中有效,但在扩展中无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60171873/

相关文章:

Facebook 请求工作需要 iPhone App Store ID?

facebook - 如何从 Facebook 帐户中删除开发人员功能?

javascript - 搜索对象的嵌套数组并返回对象的完整路径

javascript - jQuery Mobile 双页脚

c# - 如何以编程方式发布 HTML 表单并获得响应

facebook - 如何从 WebView 将数据返回给 Facebook Messenger Bot?

javascript - window.onload() 不适用于专有 fwk 生成的 html 内容

javascript - 单击按钮后关闭使用 window.open() 打开的窗口

php - DOMDocument loadHTML 在服务器上无法正常工作

javascript - Firestore - 查询并动态设置 Refs 函数