Get HTML inside iframe using jQuery

后端 未结 10 1108
清歌不尽
清歌不尽 2020-11-27 04:24

Here is my situation.

I have a file called iframe.html, which contains the code to for a image slideshow. The code is somewhat like

<         


        
相关标签:
10条回答
  • 2020-11-27 04:49
    $(editFrame).contents().find("html").html();
    
    0 讨论(0)
  • 2020-11-27 04:52

    Why not try Ajax, check a code part 1 or part 2 (use comment).

    $(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>

    0 讨论(0)
  • 2020-11-27 04:54

    Just for reference's sake. This is how to do it with JQuery (useful for instance when you cannot query by element id):

    $('#iframe').get(0).contentWindow.document.body.innerHTML
    
    0 讨论(0)
  • 2020-11-27 04:56

    This can be another solution if jquery is loaded in iframe.html.

    $('#iframe')[0].contentWindow.$("html").html()
    
    0 讨论(0)
  • 2020-11-27 04:59

    If you have Div as follows in one Iframe

     <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>
    

    Then you can find the text of those Div using the following code

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

    I hope this will help someone.

    0 讨论(0)
  • 2020-11-27 05:02

    this works for me because it works fine in ie8.

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

    but if you like to use javascript aside for jquery you may use like this

    var iframe = document.getElementById('iframecontent');
    var innerDoc = iframe.contentDocument || iframe.contentWindow.document;
    var val_1 = innerDoc.getElementById('value_1').value;
    
    0 讨论(0)
提交回复
热议问题