簡體   English   中英

用於操作 Facebook 圖像的 Javascript 代碼在控制台中有效,但在擴展中無效

[英]Javascript Code for manipulating Facebook images works in console but not in extension

我一直在嘗試創建一個基於 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. 使用document.wrappedJSObject.getElementsByTagName("img")確保關閉“x 射線”視覺

  3. 取消注冊並重新注冊 Web 擴展。

這些都沒有奏效。 有趣的是,該網絡擴展程序適用於除 facebook 之外的所有其他網站! 所以我懷疑我有兩個問題之一:

  1. Facebook 在隱藏他們的 DOM 方面做得非常出色!
  2. GeckoView 無法訪問“動態生成”圖像元素的 DOM。

任何幫助,將不勝感激 :)

我剛剛測試了它,並且擴展為書面形式對我有用。 您編寫的代碼只會在加載時捕獲頁面上預設的圖像,但 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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM