javascript google chrome 扩展 iframe 无法检查 contentWindow

标签 javascript iframe google-chrome-extension

我正在编写 Google Chrome 扩展程序。现在我需要检查 iframe 的内容,但内容脚本似乎无法访问此内容,即使调试器可以。 iframe 内容是我之前发送到该站点的消息列表。如果我将以下语句放在内容脚本中,它总是返回 null:

document.getElementById("td_messages_show").getElementsByTagName("iframe")[0].contentWindow.document;

但是如果我打开调试器并从命令行执行相同的命令,它会返回包含适当内容的“文档”。起初我以为是因为框架没有完成加载所以我找到了这样的片段并尝试使用它。

function wait4Iframe2Load() {
   // Get a handle to the iframe element
   //console.log('Checking for null myFrame');
    var myFrame = document.getElementById("td_messages_show").getElementsByTagName("iframe")[0].contentWindow;
    if (myFrame!=null) 
    {
        console.log(myFrame);
       // Check if loading is complete
       if ( myFrame.document.readyState == 'complete' ) {
          // The loading is complete, call the function we want executed once the iframe is loaded
          console.log('Loading Complete');
          //frameContent=document.getElementById("td_messages_show").getElementsByTagName("iframe")[0].contentWindow.document.getElementsByTagName('tbody')[0];
          return;
       }
       else alert(" Frame is Not Loaded");
    }
    else myFrame = document.getElementById("td_messages_show").getElementsByTagName("iframe")[0].contentWindow;
   // If we are here, it is not loaded. Set things up so we check the status again in 100 milliseconds
   console.log('Waiting for frame to load...');
   window.setTimeout('wait4Iframe2Load()', 100);      
}

这只会永远返回 null。但是当这个脚本堆积控制台消息时,我可以打开调试器并执行完全相同的命令行,它会返回一个文档。面对这个问题并研究互联网答案,这似乎是某种故意的安全问题。无论是否存在,我都需要检查 iframe 内容并确定我之前在那里写了什么,这样我才能决定接下来要在那里写什么。

有人知道如何解决这个问题吗?

最佳答案

想法是将内容脚本注入(inject)此 iframe 并使用它来获取所需信息。

据我所知,这个框架有一个预先知道的特定 url,因此您可以通过 list 注入(inject)脚本(使用 all_frames 选项)。

如果由于某种原因你需要动态注入(inject)它,那么有:

chrome.tabs.executeScript(tabId, {allFrames: true});

它将被注入(inject)父页面和 iframe 页面。然后在注入(inject)的内容脚本中,您可以检查它是否在正确的 iframe 中运行。例如,您动态注入(inject)的内容脚本可能如下所示(如果您注入(inject)它,则不需要 list url 检查):

if(window.location.href == "http://iframe.example.com/" && window != window.top) {
    //we are in the right page that is embedded as iframe, do stuff
} else {
    //do nothing
}

关于javascript google chrome 扩展 iframe 无法检查 contentWindow,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7212867/

相关文章:

javascript - 如何在循环内的元素的类之间切换?

javascript - 如何为 jquery i18n 设置字符集 utf-8?

jquery - 如何使用 jQuery 单击按钮时暂停 YouTube 视频?

google-chrome-extension - Dart Chrome 扩展 : How to send a response in onMessage?

javascript - 根据服务器响应使用 chrome.webRequest 重定向用户

javascript - ESlint - 错误 : Must use import to load ES Module

javascript - npm install 不会创建 dist 文件夹

javascript - 根据内部内容使 iframe 高度动态化- JQUERY/Javascript

node.js - 如何允许通过iframe访问我的Web应用程序中的一个URL?

javascript - Chrome 扩展程序的跟踪 URL