我一直在尝试创建一个基于 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 扩展的内容脚本时,它根本无法工作!以下是我迄今为止尝试过的所有技巧:
确保 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。
使用
document.wrappedJSObject.getElementsByTagName("img") 确保“X 射线”视觉关闭
取消注册并重新注册网络扩展。
这些都不起作用。有趣的是,该网络扩展适用于除 facebook 之外的所有其他网站! 所以我怀疑我有两个问题之一:
- Facebook 在 Conceal DOM 方面做得非常出色!
- 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/