【问题标题】:Get HTML inside iframe using jQuery使用 jQuery 在 iframe 中获取 HTML
【发布时间】:2013-04-12 18:36:24
【问题描述】:

这是我的情况。

我有一个名为iframe.html 的文件,其中包含图像幻灯片的代码。 代码有点像

<html>
  <head>
    <!-- Have added title and js files (jquery, slideshow.js) etc. -->
  </head>

  <body>
    <!-- Contains the images which are rendered as slidehow. -->
    <!-- have hierarchy like 'div' inside 'div' etc. -->
  </body>
</html>

用户可以使用嵌入代码将幻灯片添加到他们的博客或网站(可以来自不同的域)。假设用户必须在index.html 中嵌入幻灯片,他们可以通过添加以下行来添加:

<iframe id="iframe" src="path_to_iframe.html" width="480" height="320" scrolling="no" frameborder="0"></iframe>

这会将完整的 HTML 代码从 iframe.html 带到 index.html,现在我需要一种方法来访问 iframe 中的元素以调整它们的一些属性。

就像在代码中一样,iframe 的宽度和高度由用户设置为一些固定尺寸。我想将幻灯片(和包含的图像)的大小调整为 iframe 容器的大小。最好的方法是什么?

我尝试通过类似的方式从index.html 访问 iframe 组件,但没有成功

$('#iframe').contents();

但得到错误:

TypeError: 无法调用 null 的方法“内容”

所以,我想在iframe.html 中实现逻辑,其中幻灯片应该检查父级的宽度和高度并相应地设置其高度。

我很困惑,希望我的问题对大多数人来说都有意义。请随时询问进一步的解释。感谢您的帮助。

【问题讨论】:

  • 您的描述中可见的可能问题是您在iframe.html 中添加了jQuery.js 而不是index.html,而是在index.html 中编写代码
  • @Knaģis 我已将jQuery.js 文件添加到iframe.html,而不是index.html
  • 如果index.html 没有对jquery.js 的引用,则不能在现有脚本中使用$() 语法(JavaScript 引用与窗口/框架隔离)。
  • @Knaģis 我认为你可能是对的。我已经使用我接受的解决方案(使用 javascript)完成了这项工作。但是,当我使用浏览器的控制台并输入$ 时,它会返回function。我认为加载在 iframe 中的 jQuery 也可以在外部访问。

标签: jquery iframe


【解决方案1】:

这一行将检索框架的整个 HTML 代码。使用其他方法代替innerHTML可以遍历内部文档的DOM。

document.getElementById('iframe').contentWindow.document.body.innerHTML

要记住的是,这仅在帧源位于同一域中时才有效。如果它来自不同的域,跨站点脚本 (XSS) 保护将启动。

【讨论】:

  • 谢谢。 iframe 在同一个域上。上述代码返回undefined
  • 您使用的是什么浏览器和版本?
  • 我也确实在脚本中犯了一个错误 - document.innerHTML 是空的,而 document.body.innerHTML 不是。
  • 我很困惑,问的问题是 jQuery - 很重要,因为我需要在 iframe 中找到所有某个类并更改它的 CSS
  • @PandaWood,我同意答案并没有完全按照 OP 指定的“使用 jQuery”。我想你想要这样的东西:var innerDocAsJQueryObject = $(document.getElementById("iframe").contentWindow.document); 然后你可以轻松地更改 iframe 内元素的 CSS,如下所示:innerDocAsJQueryObject.find(".yourClass").css("background-color", "purple");
【解决方案2】:

试试这个代码:

$('#iframe').contents().find("html").html();

这将返回 iframe 中的所有 html。除了.find("html"),您可以使用任何您想要的选择器,例如:.find('body'),.find('div#mydiv')

【讨论】:

  • 请注意,如果 iframe 文档托管在另一个域或同一个域但端口号不同,这将不起作用。
  • 无论如何它都不会工作 - 在上面的问题中你可以看到 iframe 的 src 是本地文件
  • 帮了我大忙!
【解决方案3】:
var iframe = document.getElementById('iframe');
  $(iframe).contents().find("html").html();

【讨论】:

    【解决方案4】:
    $(editFrame).contents().find("html").html();
    

    【讨论】:

      【解决方案5】:

      这对我有用,因为它在 ie8 中运行良好。

      $('#iframe').contents().find("html").html();
      

      但如果你喜欢在 jquery 之外使用 javascript,你可以像这样使用

      var iframe = document.getElementById('iframecontent');
      var innerDoc = iframe.contentDocument || iframe.contentWindow.document;
      var val_1 = innerDoc.getElementById('value_1').value;
      

      【讨论】:

        【解决方案6】:

        如果您在一个 Iframe

        中有如下 Div
         <iframe id="ifrmReportViewer" name="ifrmReportViewer" frameborder="0" width="980"
        
             <div id="EndLetterSequenceNoToShow" runat="server"> 11441551 </div> Or
        
             <form id="form1" runat="server">        
               <div style="clear: both; width: 998px; margin: 0 auto;" id="divInnerForm">          
        
                    Some Text
        
                </div>
             </form>
         </iframe>
        

        然后你可以使用下面的代码找到那些Div的文字

        var iContentBody = $("#ifrmReportViewer").contents().find("body");
        var endLetterSequenceNo = iContentBody.find("#EndLetterSequenceNoToShow").text();
        
        var divInnerFormText = iContentBody.find("#divInnerForm").text();
        

        我希望这会对某人有所帮助。

        【讨论】:

        • iframe 内没有 div - iframe 有本地 src
        【解决方案7】:

        仅供参考。这是使用 JQuery 的方法(例如,当您无法按元素 id 查询时很有用):

        $('#iframe').get(0).contentWindow.document.body.innerHTML
        

        【讨论】:

          【解决方案8】:

          如果在 iframe.html 中加载 jquery,这可能是另一种解决方案。

          $('#iframe')[0].contentWindow.$("html").html()
          

          【讨论】:

            【解决方案9】:

            为什么不试试 Ajax,检查代码的第 1 部分或第 2 部分(使用注释)。

            $(document).ready(function(){ 
            	console.clear();
            /*
                // PART 1 ERROR
                // Uncaught SecurityError: Failed to read the 'contentDocument' property from 'HTMLIFrameElement': Sandbox access violation: Blocked a frame at "http://stacksnippets.net" from accessing a frame at "null".  Both frames are sandboxed and lack the "allow-same-origin" flag.
            	console.log("PART 1:: ");
            	console.log($('iframe#sandro').contents().find("html").html());
            */
            	// PART 2
            	$.ajax({
            		url: $("iframe#sandro").attr("src"),
            		type: 'GET',
            		dataType: 'html'
            	}).done(function(html) {
            		console.log("PART 2:: ");
            		console.log(html);
            	});
            
            });
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
            <html>
            <body>
            <iframe id="sandro" src="https://jsfiddle.net/robots.txt"></iframe>
            </body>
            </html>

            【讨论】:

            【解决方案10】:
            $('#iframe').load(function() {
                var src = $('#iframe').contents().find("html").html();
                alert(src);
            });
            

            【讨论】:

            • 请添加描述:为什么会有帮助?
            猜你喜欢
            • 2012-02-07
            • 1970-01-01
            • 2012-02-19
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2017-05-04
            • 1970-01-01
            相关资源
            最近更新 更多