簡體   English   中英

如何從Chrome擴展程序訪問iframe?

[英]How to access an iframe from chrome extension?

如何使擴展程序能夠像adblock一樣在所有框架上正常工作?

我嘗試將"all_frames" : true添加到清單文件中,但是沒有用。

我試圖使用此代碼來獲取具有特定ID的文本:

var theId = "starts with something";
var myArray = [];
$('[id^="theId"]').each(function(i, obj) {
    myArray.push($(this).text());
}); 

$.unique(myArray);

console.log(myArray);

但是它說我的數組是空的。 當我檢查頁面上的元素時,我看到一個“頂層”層和一個“目標內容”層。 該代碼僅在我在“目標內容”層上的控制台中執行時有效。 我可以在內容腳本中使用此代碼,還是需要以某種方式使用background.js?

我認為您的腳本可能在DOM加載之前就已執行,請嘗試將函數放入其中:

document.addEventListener('DOMContentLoaded', function() {

});

編輯該事件似乎在內容腳本中不起作用,我認為這是因為它們在DOM加載后已經在加載,並且從不觸發。

但是,這似乎觸發了,但不確定為什么:

$(function(){
//something
});

這也需要jQuery注入

續自SO44122853

我看到您發現內容已加載到iframe中。 所以我在這里有一個工作演示, PLUNKER ,摘錄在這里,以防萬一插手掉下來了。

詳細信息已注釋 PLUNKER

演示

由於需要運行2個單獨的頁面而無法運行

 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width,initial-scale=1, user-scalable=no"> <style></style> </head> <body> <!--iframe is same as the one on the site, with the exception of the src--> <iframe id="ptifrmtgtframe" name="TargetContent" title="Main Content" frameborder="0" scrolling="auto" width='90%' src="tables.html"></iframe> <!--The data is displayed as a one string--> <output id='display'></output> <script> // Reference the iframe var iFID = document.getElementById("ptifrmtgtframe"); // Register the load event on iframe iFID.onload = function(e) { // Callback is extractText function return extractText('#ptifrmtgtframe', '#display', '.PSLONGEDITBOX'); } /* Pass iframe and display as a single selector || Pass targets as a multiple selector */ function extractText(iframe, display, targets) { var iArray = []; var iFrame = document.querySelector(iframe); var iView = document.querySelector(display); var iNode = ""; /* .contentWindow is property that refers to content || that is in an iframe. This is the heart of the || demo. */ var iContent = iFrame.contentDocument || iFrame.contentWindow.document; var iTarget = iContent.querySelectorAll(targets); /* .map() will call a function on each element || and return a new array as well. */ Array.from(iTarget).map(function(node, idx) { iNode = node.textContent; iView.textContent += iNode; iArray.push(iNode); return iArray; }); console.log(iArray); } </script> </body> 

暫無
暫無

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

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